Prepare for merge: Move all tokio-xmpp files into tokio-xmpp/
Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>
This commit is contained in:
parent
450d43a0ee
commit
34aa710366
23 changed files with 0 additions and 0 deletions
130
tokio-xmpp/examples/contact_addr.rs
Normal file
130
tokio-xmpp/examples/contact_addr.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
use futures::{future, Sink, Stream};
|
||||
use std::convert::TryFrom;
|
||||
use std::env::args;
|
||||
use std::process::exit;
|
||||
use tokio::runtime::current_thread::Runtime;
|
||||
use tokio_xmpp::{Client, xmpp_codec::Packet};
|
||||
use xmpp_parsers::{
|
||||
Element,
|
||||
Jid,
|
||||
ns,
|
||||
iq::{
|
||||
Iq,
|
||||
IqType,
|
||||
},
|
||||
disco::{
|
||||
DiscoInfoResult,
|
||||
DiscoInfoQuery,
|
||||
},
|
||||
server_info::ServerInfo,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = args().collect();
|
||||
if args.len() != 4 {
|
||||
println!("Usage: {} <jid> <password> <target>", args[0]);
|
||||
exit(1);
|
||||
}
|
||||
let jid = &args[1];
|
||||
let password = &args[2];
|
||||
let target = &args[3];
|
||||
|
||||
// tokio_core context
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
// Client instance
|
||||
let client = Client::new(jid, password).unwrap();
|
||||
|
||||
// Make the two interfaces for sending and receiving independent
|
||||
// of each other so we can move one into a closure.
|
||||
let (mut sink, stream) = client.split();
|
||||
// Wrap sink in Option so that we can take() it for the send(self)
|
||||
// to consume and return it back when ready.
|
||||
let mut send = move |packet| {
|
||||
sink.start_send(packet).expect("start_send");
|
||||
};
|
||||
// Main loop, processes events
|
||||
let mut wait_for_stream_end = false;
|
||||
let done = stream.for_each(|event| {
|
||||
if wait_for_stream_end {
|
||||
/* Do Nothing. */
|
||||
} else if event.is_online() {
|
||||
println!("Online!");
|
||||
|
||||
let target_jid: Jid = target.clone().parse().unwrap();
|
||||
let iq = make_disco_iq(target_jid);
|
||||
println!("Sending disco#info request to {}", target.clone());
|
||||
println!(">> {}", String::from(&iq));
|
||||
send(Packet::Stanza(iq));
|
||||
} else if let Some(stanza) = event.into_stanza() {
|
||||
if stanza.is("iq", "jabber:client") {
|
||||
let iq = Iq::try_from(stanza).unwrap();
|
||||
if let IqType::Result(Some(payload)) = iq.payload {
|
||||
if payload.is("query", ns::DISCO_INFO) {
|
||||
if let Ok(disco_info) = DiscoInfoResult::try_from(payload) {
|
||||
for ext in disco_info.extensions {
|
||||
if let Ok(server_info) = ServerInfo::try_from(ext) {
|
||||
print_server_info(server_info);
|
||||
wait_for_stream_end = true;
|
||||
send(Packet::StreamEnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Box::new(future::ok(()))
|
||||
});
|
||||
|
||||
// Start polling `done`
|
||||
match rt.block_on(done) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
println!("Fatal: {}", e);
|
||||
()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_disco_iq(target: Jid) -> Element {
|
||||
Iq::from_get("disco", DiscoInfoQuery { node: None })
|
||||
.with_id(String::from("contact"))
|
||||
.with_to(target)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn convert_field(field: Vec<String>) -> String {
|
||||
field.iter()
|
||||
.fold((field.len(), String::new()), |(l, mut acc), s| {
|
||||
acc.push('<');
|
||||
acc.push_str(&s);
|
||||
acc.push('>');
|
||||
if l > 1 {
|
||||
acc.push(',');
|
||||
acc.push(' ');
|
||||
}
|
||||
(0, acc)
|
||||
}).1
|
||||
}
|
||||
|
||||
fn print_server_info(server_info: ServerInfo) {
|
||||
if server_info.abuse.len() != 0 {
|
||||
println!("abuse: {}", convert_field(server_info.abuse));
|
||||
}
|
||||
if server_info.admin.len() != 0 {
|
||||
println!("admin: {}", convert_field(server_info.admin));
|
||||
}
|
||||
if server_info.feedback.len() != 0 {
|
||||
println!("feedback: {}", convert_field(server_info.feedback));
|
||||
}
|
||||
if server_info.sales.len() != 0 {
|
||||
println!("sales: {}", convert_field(server_info.sales));
|
||||
}
|
||||
if server_info.security.len() != 0 {
|
||||
println!("security: {}", convert_field(server_info.security));
|
||||
}
|
||||
if server_info.support.len() != 0 {
|
||||
println!("support: {}", convert_field(server_info.support));
|
||||
}
|
||||
}
|
||||
232
tokio-xmpp/examples/download_avatars.rs
Normal file
232
tokio-xmpp/examples/download_avatars.rs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
use futures::{future, Future, Sink, Stream};
|
||||
use std::convert::TryFrom;
|
||||
use std::env::args;
|
||||
use std::fs::{create_dir_all, File};
|
||||
use std::io::{self, Write};
|
||||
use std::process::exit;
|
||||
use std::str::FromStr;
|
||||
use tokio::runtime::current_thread::Runtime;
|
||||
use tokio_xmpp::{Client, Packet};
|
||||
use xmpp_parsers::{
|
||||
avatar::{Data as AvatarData, Metadata as AvatarMetadata},
|
||||
caps::{compute_disco, hash_caps, Caps},
|
||||
disco::{DiscoInfoQuery, DiscoInfoResult, Feature, Identity},
|
||||
hashes::Algo,
|
||||
iq::{Iq, IqType},
|
||||
message::Message,
|
||||
ns,
|
||||
presence::{Presence, Type as PresenceType},
|
||||
pubsub::{
|
||||
event::PubSubEvent,
|
||||
pubsub::{Items, PubSub},
|
||||
NodeName,
|
||||
},
|
||||
stanza_error::{StanzaError, ErrorType, DefinedCondition},
|
||||
Jid,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = args().collect();
|
||||
if args.len() != 3 {
|
||||
println!("Usage: {} <jid> <password>", args[0]);
|
||||
exit(1);
|
||||
}
|
||||
let jid = &args[1];
|
||||
let password = &args[2];
|
||||
|
||||
// tokio_core context
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
// Client instance
|
||||
let client = Client::new(jid, password).unwrap();
|
||||
|
||||
// Make the two interfaces for sending and receiving independent
|
||||
// of each other so we can move one into a closure.
|
||||
let (sink, stream) = client.split();
|
||||
|
||||
// Create outgoing pipe
|
||||
let (mut tx, rx) = futures::unsync::mpsc::unbounded();
|
||||
rt.spawn(
|
||||
rx.forward(
|
||||
sink.sink_map_err(|_| panic!("Pipe"))
|
||||
)
|
||||
.map(|(rx, mut sink)| {
|
||||
drop(rx);
|
||||
let _ = sink.close();
|
||||
})
|
||||
.map_err(|e| {
|
||||
panic!("Send error: {:?}", e);
|
||||
})
|
||||
);
|
||||
|
||||
let disco_info = make_disco();
|
||||
|
||||
// Main loop, processes events
|
||||
let mut wait_for_stream_end = false;
|
||||
let done = stream.for_each(move |event| {
|
||||
// Helper function to send an iq error.
|
||||
let mut send_error = |to, id, type_, condition, text: &str| {
|
||||
let error = StanzaError::new(type_, condition, "en", text);
|
||||
let iq = Iq::from_error(id, error)
|
||||
.with_to(to);
|
||||
tx.start_send(Packet::Stanza(iq.into())).unwrap();
|
||||
};
|
||||
|
||||
if wait_for_stream_end {
|
||||
/* Do nothing */
|
||||
} else if event.is_online() {
|
||||
println!("Online!");
|
||||
|
||||
let caps = get_disco_caps(&disco_info, "https://gitlab.com/xmpp-rs/tokio-xmpp");
|
||||
let presence = make_presence(caps);
|
||||
tx.start_send(Packet::Stanza(presence.into())).unwrap();
|
||||
} else if let Some(stanza) = event.into_stanza() {
|
||||
if stanza.is("iq", "jabber:client") {
|
||||
let iq = Iq::try_from(stanza).unwrap();
|
||||
if let IqType::Get(payload) = iq.payload {
|
||||
if payload.is("query", ns::DISCO_INFO) {
|
||||
let query = DiscoInfoQuery::try_from(payload);
|
||||
match query {
|
||||
Ok(query) => {
|
||||
let mut disco = disco_info.clone();
|
||||
disco.node = query.node;
|
||||
let iq = Iq::from_result(iq.id, Some(disco))
|
||||
.with_to(iq.from.unwrap());
|
||||
tx.start_send(Packet::Stanza(iq.into())).unwrap();
|
||||
},
|
||||
Err(err) => {
|
||||
send_error(iq.from.unwrap(), iq.id, ErrorType::Modify, DefinedCondition::BadRequest, &format!("{}", err));
|
||||
},
|
||||
}
|
||||
} else {
|
||||
// We MUST answer unhandled get iqs with a service-unavailable error.
|
||||
send_error(iq.from.unwrap(), iq.id, ErrorType::Cancel, DefinedCondition::ServiceUnavailable, "No handler defined for this kind of iq.");
|
||||
}
|
||||
} else if let IqType::Result(Some(payload)) = iq.payload {
|
||||
if payload.is("pubsub", ns::PUBSUB) {
|
||||
let pubsub = PubSub::try_from(payload).unwrap();
|
||||
let from =
|
||||
iq.from.clone().unwrap_or(Jid::from_str(jid).unwrap());
|
||||
handle_iq_result(pubsub, &from);
|
||||
}
|
||||
} else if let IqType::Set(_) = iq.payload {
|
||||
// We MUST answer unhandled set iqs with a service-unavailable error.
|
||||
send_error(iq.from.unwrap(), iq.id, ErrorType::Cancel, DefinedCondition::ServiceUnavailable, "No handler defined for this kind of iq.");
|
||||
}
|
||||
} else if stanza.is("message", "jabber:client") {
|
||||
let message = Message::try_from(stanza).unwrap();
|
||||
let from = message.from.clone().unwrap();
|
||||
if let Some(body) = message.get_best_body(vec!["en"]) {
|
||||
if body.1 .0 == "die" {
|
||||
println!("Secret die command triggered by {}", from);
|
||||
wait_for_stream_end = true;
|
||||
tx.start_send(Packet::StreamEnd).unwrap();
|
||||
}
|
||||
}
|
||||
for child in message.payloads {
|
||||
if child.is("event", ns::PUBSUB_EVENT) {
|
||||
let event = PubSubEvent::try_from(child).unwrap();
|
||||
if let PubSubEvent::PublishedItems { node, items } = event {
|
||||
if node.0 == ns::AVATAR_METADATA {
|
||||
for item in items.into_iter() {
|
||||
let payload = item.payload.clone().unwrap();
|
||||
if payload.is("metadata", ns::AVATAR_METADATA) {
|
||||
// TODO: do something with these metadata.
|
||||
let _metadata = AvatarMetadata::try_from(payload).unwrap();
|
||||
println!(
|
||||
"[1m{}[0m has published an avatar, downloading...",
|
||||
from.clone()
|
||||
);
|
||||
let iq = download_avatar(from.clone());
|
||||
tx.start_send(Packet::Stanza(iq.into())).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if stanza.is("presence", "jabber:client") {
|
||||
// Nothing to do here.
|
||||
} else {
|
||||
panic!("Unknown stanza: {}", String::from(&stanza));
|
||||
}
|
||||
}
|
||||
|
||||
future::ok(())
|
||||
});
|
||||
|
||||
// Start polling `done`
|
||||
match rt.block_on(done) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
println!("Fatal: {}", e);
|
||||
()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_disco() -> DiscoInfoResult {
|
||||
let identities = vec![Identity::new("client", "bot", "en", "tokio-xmpp")];
|
||||
let features = vec![
|
||||
Feature::new(ns::DISCO_INFO),
|
||||
Feature::new(format!("{}+notify", ns::AVATAR_METADATA)),
|
||||
];
|
||||
DiscoInfoResult {
|
||||
node: None,
|
||||
identities,
|
||||
features,
|
||||
extensions: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn get_disco_caps(disco: &DiscoInfoResult, node: &str) -> Caps {
|
||||
let caps_data = compute_disco(disco);
|
||||
let hash = hash_caps(&caps_data, Algo::Sha_1).unwrap();
|
||||
Caps::new(node, hash)
|
||||
}
|
||||
|
||||
// Construct a <presence/>
|
||||
fn make_presence(caps: Caps) -> Presence {
|
||||
let mut presence = Presence::new(PresenceType::None)
|
||||
.with_priority(-1);
|
||||
presence.set_status("en", "Downloading avatars.");
|
||||
presence.add_payload(caps);
|
||||
presence
|
||||
}
|
||||
|
||||
fn download_avatar(from: Jid) -> Iq {
|
||||
Iq::from_get("coucou", PubSub::Items(Items {
|
||||
max_items: None,
|
||||
node: NodeName(String::from(ns::AVATAR_DATA)),
|
||||
subid: None,
|
||||
items: Vec::new(),
|
||||
}))
|
||||
.with_to(from)
|
||||
}
|
||||
|
||||
fn handle_iq_result(pubsub: PubSub, from: &Jid) {
|
||||
if let PubSub::Items(items) = pubsub {
|
||||
if items.node.0 == ns::AVATAR_DATA {
|
||||
for item in items.items {
|
||||
match (item.id.clone(), item.payload.clone()) {
|
||||
(Some(id), Some(payload)) => {
|
||||
let data = AvatarData::try_from(payload).unwrap();
|
||||
save_avatar(from, id.0, &data.data).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_avatar(from: &Jid, id: String, data: &[u8]) -> io::Result<()> {
|
||||
let directory = format!("data/{}", from);
|
||||
let filename = format!("data/{}/{}", from, id);
|
||||
println!(
|
||||
"Saving avatar from [1m{}[0m to [4m{}[0m.",
|
||||
from, filename
|
||||
);
|
||||
create_dir_all(directory)?;
|
||||
let mut file = File::create(filename)?;
|
||||
file.write_all(data)
|
||||
}
|
||||
106
tokio-xmpp/examples/echo_bot.rs
Normal file
106
tokio-xmpp/examples/echo_bot.rs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
use futures::{future, Future, Sink, Stream};
|
||||
use std::convert::TryFrom;
|
||||
use std::env::args;
|
||||
use std::process::exit;
|
||||
use tokio::runtime::current_thread::Runtime;
|
||||
use tokio_xmpp::{Client, Packet};
|
||||
use xmpp_parsers::{Jid, Element};
|
||||
use xmpp_parsers::message::{Body, Message, MessageType};
|
||||
use xmpp_parsers::presence::{Presence, Show as PresenceShow, Type as PresenceType};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = args().collect();
|
||||
if args.len() != 3 {
|
||||
println!("Usage: {} <jid> <password>", args[0]);
|
||||
exit(1);
|
||||
}
|
||||
let jid = &args[1];
|
||||
let password = &args[2];
|
||||
|
||||
// tokio_core context
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
// Client instance
|
||||
let client = Client::new(jid, password).unwrap();
|
||||
|
||||
// Make the two interfaces for sending and receiving independent
|
||||
// of each other so we can move one into a closure.
|
||||
let (sink, stream) = client.split();
|
||||
|
||||
// Create outgoing pipe
|
||||
let (mut tx, rx) = futures::unsync::mpsc::unbounded();
|
||||
rt.spawn(
|
||||
rx.forward(
|
||||
sink.sink_map_err(|_| panic!("Pipe"))
|
||||
)
|
||||
.map(|(rx, mut sink)| {
|
||||
drop(rx);
|
||||
let _ = sink.close();
|
||||
})
|
||||
.map_err(|e| {
|
||||
panic!("Send error: {:?}", e);
|
||||
})
|
||||
);
|
||||
|
||||
// Main loop, processes events
|
||||
let mut wait_for_stream_end = false;
|
||||
let done = stream.for_each(move |event| {
|
||||
if wait_for_stream_end {
|
||||
/* Do nothing */
|
||||
} else if event.is_online() {
|
||||
let jid = event.get_jid()
|
||||
.map(|jid| format!("{}", jid))
|
||||
.unwrap_or("unknown".to_owned());
|
||||
println!("Online at {}", jid);
|
||||
|
||||
let presence = make_presence();
|
||||
tx.start_send(Packet::Stanza(presence)).unwrap();
|
||||
} else if let Some(message) = event
|
||||
.into_stanza()
|
||||
.and_then(|stanza| Message::try_from(stanza).ok())
|
||||
{
|
||||
match (message.from, message.bodies.get("")) {
|
||||
(Some(ref from), Some(ref body)) if body.0 == "die" => {
|
||||
println!("Secret die command triggered by {}", from);
|
||||
wait_for_stream_end = true;
|
||||
tx.start_send(Packet::StreamEnd).unwrap();
|
||||
}
|
||||
(Some(ref from), Some(ref body)) => {
|
||||
if message.type_ != MessageType::Error {
|
||||
// This is a message we'll echo
|
||||
let reply = make_reply(from.clone(), &body.0);
|
||||
tx.start_send(Packet::Stanza(reply)).unwrap();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
future::ok(())
|
||||
});
|
||||
|
||||
// Start polling `done`
|
||||
match rt.block_on(done) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
println!("Fatal: {}", e);
|
||||
()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Construct a <presence/>
|
||||
fn make_presence() -> Element {
|
||||
let mut presence = Presence::new(PresenceType::None);
|
||||
presence.show = Some(PresenceShow::Chat);
|
||||
presence
|
||||
.statuses
|
||||
.insert(String::from("en"), String::from("Echoing messages."));
|
||||
presence.into()
|
||||
}
|
||||
|
||||
// Construct a chat <message/>
|
||||
fn make_reply(to: Jid, body: &str) -> Element {
|
||||
let mut message = Message::new(Some(to));
|
||||
message.bodies.insert(String::new(), Body(body.to_owned()));
|
||||
message.into()
|
||||
}
|
||||
99
tokio-xmpp/examples/echo_component.rs
Normal file
99
tokio-xmpp/examples/echo_component.rs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
use futures::{future, Sink, Stream};
|
||||
use std::convert::TryFrom;
|
||||
use std::env::args;
|
||||
use std::process::exit;
|
||||
use std::str::FromStr;
|
||||
use tokio::runtime::current_thread::Runtime;
|
||||
use tokio_xmpp::Component;
|
||||
use xmpp_parsers::{Jid, Element};
|
||||
use xmpp_parsers::message::{Body, Message, MessageType};
|
||||
use xmpp_parsers::presence::{Presence, Show as PresenceShow, Type as PresenceType};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = args().collect();
|
||||
if args.len() < 3 || args.len() > 5 {
|
||||
println!("Usage: {} <jid> <password> [server] [port]", args[0]);
|
||||
exit(1);
|
||||
}
|
||||
let jid = &args[1];
|
||||
let password = &args[2];
|
||||
let server = &args
|
||||
.get(3)
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap_or("127.0.0.1".to_owned());
|
||||
let port: u16 = args.get(4).unwrap().parse().unwrap_or(5347u16);
|
||||
|
||||
// tokio_core context
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
// Component instance
|
||||
println!("{} {} {} {}", jid, password, server, port);
|
||||
let component = Component::new(jid, password, server, port).unwrap();
|
||||
|
||||
// Make the two interfaces for sending and receiving independent
|
||||
// of each other so we can move one into a closure.
|
||||
println!("Got it: {}", component.jid.clone());
|
||||
let (mut sink, stream) = component.split();
|
||||
// Wrap sink in Option so that we can take() it for the send(self)
|
||||
// to consume and return it back when ready.
|
||||
let mut send = move |stanza| {
|
||||
sink.start_send(stanza).expect("start_send");
|
||||
};
|
||||
// Main loop, processes events
|
||||
let done = stream.for_each(|event| {
|
||||
if event.is_online() {
|
||||
println!("Online!");
|
||||
|
||||
// TODO: replace these hardcoded JIDs
|
||||
let presence = make_presence(
|
||||
Jid::from_str("test@component.linkmauve.fr/coucou").unwrap(),
|
||||
Jid::from_str("linkmauve@linkmauve.fr").unwrap(),
|
||||
);
|
||||
send(presence);
|
||||
} else if let Some(message) = event
|
||||
.into_stanza()
|
||||
.and_then(|stanza| Message::try_from(stanza).ok())
|
||||
{
|
||||
// This is a message we'll echo
|
||||
match (message.from, message.bodies.get("")) {
|
||||
(Some(from), Some(body)) => {
|
||||
if message.type_ != MessageType::Error {
|
||||
let reply = make_reply(from, &body.0);
|
||||
send(reply);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
Box::new(future::ok(()))
|
||||
});
|
||||
|
||||
// Start polling `done`
|
||||
match rt.block_on(done) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
println!("Fatal: {}", e);
|
||||
()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Construct a <presence/>
|
||||
fn make_presence(from: Jid, to: Jid) -> Element {
|
||||
let mut presence = Presence::new(PresenceType::None);
|
||||
presence.from = Some(from);
|
||||
presence.to = Some(to);
|
||||
presence.show = Some(PresenceShow::Chat);
|
||||
presence
|
||||
.statuses
|
||||
.insert(String::from("en"), String::from("Echoing messages."));
|
||||
presence.into()
|
||||
}
|
||||
|
||||
// Construct a chat <message/>
|
||||
fn make_reply(to: Jid, body: &str) -> Element {
|
||||
let mut message = Message::new(Some(to));
|
||||
message.bodies.insert(String::new(), Body(body.to_owned()));
|
||||
message.into()
|
||||
}
|
||||
Loading…
Reference in a new issue