2019-03-21 17:41:29 +00:00
|
|
|
// Copyright (c) 2019 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
|
2019-07-25 13:03:22 +00:00
|
|
|
#![deny(bare_trait_objects)]
|
|
|
|
|
2020-03-08 18:57:59 +00:00
|
|
|
use futures::stream::StreamExt;
|
2021-12-26 23:48:37 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
2023-06-01 09:44:49 +00:00
|
|
|
use std::sync::{Arc, RwLock};
|
2021-12-26 23:48:37 +00:00
|
|
|
use tokio::fs::File;
|
2023-08-21 08:57:33 +00:00
|
|
|
pub use tokio_xmpp::parsers;
|
2023-08-17 14:17:53 +00:00
|
|
|
use tokio_xmpp::parsers::{
|
2023-12-29 20:56:37 +00:00
|
|
|
bookmarks,
|
2019-03-21 17:41:29 +00:00
|
|
|
caps::{compute_disco, hash_caps, Caps},
|
2023-12-29 19:58:26 +00:00
|
|
|
disco::{DiscoInfoQuery, DiscoInfoResult, Feature},
|
2019-03-21 17:41:29 +00:00
|
|
|
hashes::Algo,
|
2023-12-29 17:29:22 +00:00
|
|
|
http_upload::SlotRequest,
|
2023-12-29 17:18:38 +00:00
|
|
|
iq::Iq,
|
2019-10-22 23:32:41 +00:00
|
|
|
message::{Body, Message, MessageType},
|
2023-12-29 17:08:04 +00:00
|
|
|
muc::{user::MucUser, Muc},
|
2019-03-21 17:41:29 +00:00
|
|
|
ns,
|
|
|
|
presence::{Presence, Type as PresenceType},
|
2023-12-16 15:06:38 +00:00
|
|
|
private::Query as PrivateXMLQuery,
|
2019-10-22 23:32:41 +00:00
|
|
|
pubsub::pubsub::{Items, PubSub},
|
2023-12-29 20:56:37 +00:00
|
|
|
roster::Roster,
|
2023-12-16 19:01:17 +00:00
|
|
|
Error as ParsersError,
|
2019-03-21 17:41:29 +00:00
|
|
|
};
|
2023-08-17 14:17:53 +00:00
|
|
|
use tokio_xmpp::{AsyncClient as TokioXmppClient, Event as TokioXmppEvent};
|
2023-08-21 08:57:33 +00:00
|
|
|
pub use tokio_xmpp::{BareJid, Element, FullJid, Jid};
|
2019-09-29 02:08:56 +00:00
|
|
|
#[macro_use]
|
|
|
|
extern crate log;
|
2019-03-21 17:41:29 +00:00
|
|
|
|
2023-12-29 19:58:26 +00:00
|
|
|
pub mod builder;
|
2023-12-29 20:56:37 +00:00
|
|
|
pub mod event;
|
2023-12-29 20:41:09 +00:00
|
|
|
pub mod feature;
|
2023-12-29 17:18:38 +00:00
|
|
|
pub mod iq;
|
2023-12-29 17:08:04 +00:00
|
|
|
pub mod message;
|
|
|
|
pub mod presence;
|
|
|
|
pub mod pubsub;
|
2023-12-29 17:29:22 +00:00
|
|
|
pub mod upload;
|
2019-03-21 17:41:29 +00:00
|
|
|
|
2023-12-29 19:58:26 +00:00
|
|
|
// Module re-exports
|
|
|
|
pub use builder::{ClientBuilder, ClientType};
|
2023-12-29 20:56:37 +00:00
|
|
|
pub use event::Event;
|
2023-12-29 20:41:09 +00:00
|
|
|
pub use feature::ClientFeature;
|
2019-03-21 17:41:29 +00:00
|
|
|
|
2023-12-29 19:58:26 +00:00
|
|
|
pub type Error = tokio_xmpp::Error;
|
|
|
|
pub type Id = Option<String>;
|
|
|
|
pub type RoomNick = String;
|
2019-03-21 17:41:29 +00:00
|
|
|
|
2019-07-05 16:59:05 +00:00
|
|
|
pub struct Agent {
|
2020-03-08 18:57:59 +00:00
|
|
|
client: TokioXmppClient,
|
2023-06-01 09:44:49 +00:00
|
|
|
default_nick: Arc<RwLock<String>>,
|
|
|
|
lang: Arc<Vec<String>>,
|
2020-03-08 18:57:59 +00:00
|
|
|
disco: DiscoInfoResult,
|
|
|
|
node: String,
|
2021-12-26 23:48:37 +00:00
|
|
|
uploads: Vec<(String, Jid, PathBuf)>,
|
2023-12-16 15:47:10 +00:00
|
|
|
awaiting_disco_bookmarks_type: bool,
|
2019-07-05 16:59:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Agent {
|
2021-12-26 23:50:23 +00:00
|
|
|
pub async fn disconnect(&mut self) -> Result<(), Error> {
|
|
|
|
self.client.send_end().await
|
|
|
|
}
|
|
|
|
|
2020-03-08 18:57:59 +00:00
|
|
|
pub async fn join_room(
|
2019-10-22 23:32:41 +00:00
|
|
|
&mut self,
|
|
|
|
room: BareJid,
|
|
|
|
nick: Option<String>,
|
|
|
|
password: Option<String>,
|
|
|
|
lang: &str,
|
|
|
|
status: &str,
|
|
|
|
) {
|
2019-07-25 13:11:39 +00:00
|
|
|
let mut muc = Muc::new();
|
|
|
|
if let Some(password) = password {
|
|
|
|
muc = muc.with_password(password);
|
|
|
|
}
|
|
|
|
|
2023-06-01 09:44:49 +00:00
|
|
|
let nick = nick.unwrap_or_else(|| self.default_nick.read().unwrap().clone());
|
2023-06-21 16:30:25 +00:00
|
|
|
let room_jid = room.with_resource_str(&nick).unwrap();
|
2023-06-20 12:51:13 +00:00
|
|
|
let mut presence = Presence::new(PresenceType::None).with_to(room_jid);
|
2019-07-25 13:11:39 +00:00
|
|
|
presence.add_payload(muc);
|
2019-03-21 17:41:29 +00:00
|
|
|
presence.set_status(String::from(lang), String::from(status));
|
2020-03-08 18:57:59 +00:00
|
|
|
let _ = self.client.send_stanza(presence.into()).await;
|
2019-03-21 17:41:29 +00:00
|
|
|
}
|
|
|
|
|
2023-12-09 12:26:23 +00:00
|
|
|
/// Send a "leave room" request to the server (specifically, an "unavailable" presence stanza).
|
2023-12-08 18:38:52 +00:00
|
|
|
///
|
|
|
|
/// The returned future will resolve when the request has been sent,
|
|
|
|
/// not when the room has actually been left.
|
|
|
|
///
|
|
|
|
/// If successful, a `RoomLeft` event should be received later as a confirmation.
|
|
|
|
///
|
|
|
|
/// See: https://xmpp.org/extensions/xep-0045.html#exit
|
|
|
|
///
|
2023-12-09 12:26:23 +00:00
|
|
|
/// Note that this method does NOT remove the room from the auto-join list; the latter
|
|
|
|
/// is more a list of bookmarks that the account knows about and that have a flag set
|
|
|
|
/// to indicate that they should be joined automatically after connecting (see the JoinRoom event).
|
|
|
|
///
|
2023-12-09 12:29:32 +00:00
|
|
|
/// Regarding the latter, see the these minutes about auto-join behavior:
|
|
|
|
/// https://docs.modernxmpp.org/meetings/2019-01-brussels/#bookmarks
|
|
|
|
///
|
2023-12-08 18:38:52 +00:00
|
|
|
/// # Arguments
|
|
|
|
///
|
2023-12-08 19:21:28 +00:00
|
|
|
/// * `room_jid`: The JID of the room to leave.
|
|
|
|
/// * `nickname`: The nickname to use in the room.
|
2023-12-08 18:38:52 +00:00
|
|
|
/// * `lang`: The language of the status message.
|
|
|
|
/// * `status`: The status message to send.
|
2023-12-08 19:02:52 +00:00
|
|
|
pub async fn leave_room(
|
|
|
|
&mut self,
|
2023-12-08 19:21:28 +00:00
|
|
|
room_jid: BareJid,
|
|
|
|
nickname: RoomNick,
|
2023-12-08 19:02:52 +00:00
|
|
|
lang: impl Into<String>,
|
|
|
|
status: impl Into<String>,
|
|
|
|
) {
|
2023-12-08 19:21:28 +00:00
|
|
|
// XEP-0045 specifies that, to leave a room, the client must send a presence stanza
|
|
|
|
// with type="unavailable".
|
|
|
|
let mut presence = Presence::new(PresenceType::Unavailable).with_to(
|
|
|
|
room_jid
|
|
|
|
.with_resource_str(nickname.as_str())
|
|
|
|
.expect("Invalid room JID after adding resource part."),
|
|
|
|
);
|
2023-12-08 18:38:52 +00:00
|
|
|
|
|
|
|
// Optionally, the client may include a status message in the presence stanza.
|
|
|
|
// TODO: Should this be optional? The XEP says "MAY", but the method signature requires the arguments.
|
2023-12-08 19:21:28 +00:00
|
|
|
// XEP-0045: "The occupant MAY include normal <status/> information in the unavailable presence stanzas"
|
2023-12-08 18:38:52 +00:00
|
|
|
presence.set_status(lang, status);
|
|
|
|
|
|
|
|
// Send the presence stanza.
|
|
|
|
if let Err(e) = self.client.send_stanza(presence.into()).await {
|
|
|
|
// Report any errors to the log.
|
|
|
|
error!("Failed to send leave room presence: {}", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-08 18:57:59 +00:00
|
|
|
pub async fn send_message(
|
|
|
|
&mut self,
|
|
|
|
recipient: Jid,
|
|
|
|
type_: MessageType,
|
|
|
|
lang: &str,
|
|
|
|
text: &str,
|
|
|
|
) {
|
2019-03-21 17:41:29 +00:00
|
|
|
let mut message = Message::new(Some(recipient));
|
|
|
|
message.type_ = type_;
|
2019-10-22 23:32:41 +00:00
|
|
|
message
|
|
|
|
.bodies
|
|
|
|
.insert(String::from(lang), Body(String::from(text)));
|
2020-03-08 18:57:59 +00:00
|
|
|
let _ = self.client.send_stanza(message.into()).await;
|
|
|
|
}
|
|
|
|
|
2023-06-07 14:38:03 +00:00
|
|
|
pub async fn send_room_private_message(
|
|
|
|
&mut self,
|
|
|
|
room: BareJid,
|
|
|
|
recipient: RoomNick,
|
|
|
|
lang: &str,
|
|
|
|
text: &str,
|
|
|
|
) {
|
2023-06-21 16:30:25 +00:00
|
|
|
let recipient: Jid = room.with_resource_str(&recipient).unwrap().into();
|
2023-06-20 12:51:13 +00:00
|
|
|
let mut message = Message::new(recipient).with_payload(MucUser::new());
|
2023-06-07 16:51:12 +00:00
|
|
|
message.type_ = MessageType::Chat;
|
|
|
|
message
|
|
|
|
.bodies
|
|
|
|
.insert(String::from(lang), Body(String::from(text)));
|
|
|
|
let _ = self.client.send_stanza(message.into()).await;
|
2023-06-07 14:38:03 +00:00
|
|
|
}
|
|
|
|
|
2020-03-08 18:57:59 +00:00
|
|
|
fn make_initial_presence(disco: &DiscoInfoResult, node: &str) -> Presence {
|
|
|
|
let caps_data = compute_disco(disco);
|
|
|
|
let hash = hash_caps(&caps_data, Algo::Sha_1).unwrap();
|
|
|
|
let caps = Caps::new(node, hash);
|
|
|
|
|
|
|
|
let mut presence = Presence::new(PresenceType::None);
|
|
|
|
presence.add_payload(caps);
|
|
|
|
presence
|
|
|
|
}
|
|
|
|
|
2023-12-16 19:01:17 +00:00
|
|
|
// This method is a workaround due to prosody bug https://issues.prosody.im/1664
|
|
|
|
// FIXME: To be removed in the future
|
|
|
|
// The server doesn't return disco#info feature when querying the account
|
|
|
|
// so we add it manually because we know it's true
|
|
|
|
async fn handle_disco_info_result_payload(&mut self, payload: Element, from: Jid) {
|
|
|
|
match DiscoInfoResult::try_from(payload.clone()) {
|
|
|
|
Ok(disco) => {
|
|
|
|
self.handle_disco_info_result(disco, from).await;
|
|
|
|
}
|
|
|
|
Err(e) => match e {
|
|
|
|
ParsersError::ParseError(reason) => {
|
|
|
|
if reason == "disco#info feature not present in disco#info." {
|
|
|
|
let mut payload = payload.clone();
|
|
|
|
let disco_feature =
|
|
|
|
Feature::new("http://jabber.org/protocol/disco#info").into();
|
|
|
|
payload.append_child(disco_feature);
|
|
|
|
match DiscoInfoResult::try_from(payload) {
|
|
|
|
Ok(disco) => {
|
|
|
|
self.handle_disco_info_result(disco, from).await;
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
panic!("Wrong disco#info format after workaround: {}", e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
panic!(
|
|
|
|
"Wrong disco#info format (reason cannot be worked around): {}",
|
|
|
|
e
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => panic!("Wrong disco#info format: {}", e),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_disco_info_result(&mut self, disco: DiscoInfoResult, from: Jid) {
|
|
|
|
// Safe unwrap because no DISCO is received when we are not online
|
|
|
|
if from == self.client.bound_jid().unwrap().to_bare() && self.awaiting_disco_bookmarks_type
|
|
|
|
{
|
|
|
|
info!("Received disco info about bookmarks type");
|
|
|
|
// Trigger bookmarks query
|
|
|
|
// TODO: only send this when the JoinRooms feature is enabled.
|
|
|
|
self.awaiting_disco_bookmarks_type = false;
|
|
|
|
let mut perform_bookmarks2 = false;
|
|
|
|
info!("{:#?}", disco.features);
|
|
|
|
for feature in disco.features {
|
|
|
|
if feature.var == "urn:xmpp:bookmarks:1#compat" {
|
|
|
|
perform_bookmarks2 = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if perform_bookmarks2 {
|
|
|
|
// XEP-0402 bookmarks (modern)
|
|
|
|
let iq =
|
|
|
|
Iq::from_get("bookmarks", PubSub::Items(Items::new(ns::BOOKMARKS2))).into();
|
|
|
|
let _ = self.client.send_stanza(iq).await;
|
|
|
|
} else {
|
|
|
|
// XEP-0048 v1.0 bookmarks (legacy)
|
|
|
|
let iq = Iq::from_get(
|
|
|
|
"bookmarks-legacy",
|
|
|
|
PrivateXMLQuery {
|
|
|
|
storage: bookmarks::Storage::new(),
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.into();
|
|
|
|
let _ = self.client.send_stanza(iq).await;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
unimplemented!("Ignored disco#info response from {}", from);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-03 21:51:36 +00:00
|
|
|
/// Wait for new events.
|
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
///
|
|
|
|
/// - `Some(events)` if there are new events; multiple may be returned at once.
|
|
|
|
/// - `None` if the underlying stream is closed.
|
2020-03-08 18:57:59 +00:00
|
|
|
pub async fn wait_for_events(&mut self) -> Option<Vec<Event>> {
|
|
|
|
if let Some(event) = self.client.next().await {
|
|
|
|
let mut events = Vec::new();
|
|
|
|
|
|
|
|
match event {
|
2020-05-29 22:24:58 +00:00
|
|
|
TokioXmppEvent::Online { resumed: false, .. } => {
|
2020-03-08 18:57:59 +00:00
|
|
|
let presence = Self::make_initial_presence(&self.disco, &self.node).into();
|
|
|
|
let _ = self.client.send_stanza(presence).await;
|
|
|
|
events.push(Event::Online);
|
|
|
|
// TODO: only send this when the ContactList feature is enabled.
|
|
|
|
let iq = Iq::from_get(
|
|
|
|
"roster",
|
|
|
|
Roster {
|
|
|
|
ver: None,
|
|
|
|
items: vec![],
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.into();
|
|
|
|
let _ = self.client.send_stanza(iq).await;
|
2023-12-16 15:47:10 +00:00
|
|
|
|
|
|
|
// Query account disco to know what bookmarks spec is used
|
|
|
|
let iq = Iq::from_get("disco-account", DiscoInfoQuery { node: None }).into();
|
2020-03-08 18:57:59 +00:00
|
|
|
let _ = self.client.send_stanza(iq).await;
|
2023-12-16 15:47:10 +00:00
|
|
|
self.awaiting_disco_bookmarks_type = true;
|
2020-03-08 18:57:59 +00:00
|
|
|
}
|
2020-05-29 22:24:58 +00:00
|
|
|
TokioXmppEvent::Online { resumed: true, .. } => {}
|
2023-12-11 12:48:39 +00:00
|
|
|
TokioXmppEvent::Disconnected(e) => {
|
|
|
|
events.push(Event::Disconnected(e));
|
2020-03-08 18:57:59 +00:00
|
|
|
}
|
2020-09-07 07:56:04 +00:00
|
|
|
TokioXmppEvent::Stanza(elem) => {
|
|
|
|
if elem.is("iq", "jabber:client") {
|
|
|
|
let iq = Iq::try_from(elem).unwrap();
|
2023-12-29 17:18:38 +00:00
|
|
|
let new_events = iq::handle_iq(self, iq).await;
|
2020-09-07 09:41:40 +00:00
|
|
|
events.extend(new_events);
|
2020-09-07 07:56:04 +00:00
|
|
|
} else if elem.is("message", "jabber:client") {
|
|
|
|
let message = Message::try_from(elem).unwrap();
|
2023-12-29 16:55:08 +00:00
|
|
|
let new_events = message::handle_message(self, message).await;
|
2020-09-07 07:56:04 +00:00
|
|
|
events.extend(new_events);
|
|
|
|
} else if elem.is("presence", "jabber:client") {
|
|
|
|
let presence = Presence::try_from(elem).unwrap();
|
2023-12-29 17:08:04 +00:00
|
|
|
let new_events = presence::handle_presence(self, presence).await;
|
2020-09-07 07:56:04 +00:00
|
|
|
events.extend(new_events);
|
|
|
|
} else if elem.is("error", "http://etherx.jabber.org/streams") {
|
|
|
|
println!("Received a fatal stream error: {}", String::from(&elem));
|
2020-03-08 18:57:59 +00:00
|
|
|
} else {
|
2020-09-07 07:56:04 +00:00
|
|
|
panic!("Unknown stanza: {}", String::from(&elem));
|
2020-03-08 18:57:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(events)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2019-03-21 17:41:29 +00:00
|
|
|
}
|
2021-12-26 23:48:37 +00:00
|
|
|
|
|
|
|
pub async fn upload_file_with(&mut self, service: &str, path: &Path) {
|
|
|
|
let name = path.file_name().unwrap().to_str().unwrap().to_string();
|
|
|
|
let file = File::open(path).await.unwrap();
|
|
|
|
let size = file.metadata().await.unwrap().len();
|
|
|
|
let slot_request = SlotRequest {
|
|
|
|
filename: name,
|
|
|
|
size: size,
|
|
|
|
content_type: None,
|
|
|
|
};
|
|
|
|
let to = service.parse::<Jid>().unwrap();
|
|
|
|
let request = Iq::from_get("upload1", slot_request).with_to(to.clone());
|
|
|
|
self.uploads
|
|
|
|
.push((String::from("upload1"), to, path.to_path_buf()));
|
|
|
|
self.client.send_stanza(request.into()).await.unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-22 21:46:50 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-06-01 09:58:04 +00:00
|
|
|
use super::{Agent, BareJid, ClientBuilder, ClientFeature, ClientType, Event};
|
|
|
|
use std::str::FromStr;
|
2020-05-29 22:24:58 +00:00
|
|
|
use tokio_xmpp::AsyncClient as TokioXmppClient;
|
2019-10-22 21:46:50 +00:00
|
|
|
|
2020-03-08 18:57:59 +00:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_simple() {
|
2023-06-01 09:58:04 +00:00
|
|
|
let jid = BareJid::from_str("foo@bar").unwrap();
|
|
|
|
|
|
|
|
let client = TokioXmppClient::new(jid.clone(), "meh");
|
2019-10-22 21:46:50 +00:00
|
|
|
|
|
|
|
// Client instance
|
2023-06-01 09:58:04 +00:00
|
|
|
let client_builder = ClientBuilder::new(jid, "meh")
|
2019-10-22 21:46:50 +00:00
|
|
|
.set_client(ClientType::Bot, "xmpp-rs")
|
|
|
|
.set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
|
|
|
|
.set_default_nick("bot")
|
|
|
|
.enable_feature(ClientFeature::ContactList);
|
|
|
|
|
2023-08-17 20:29:04 +00:00
|
|
|
#[cfg(feature = "avatars")]
|
|
|
|
let client_builder = client_builder.enable_feature(ClientFeature::Avatars);
|
|
|
|
|
2023-06-01 09:58:04 +00:00
|
|
|
let mut agent: Agent = client_builder.build_impl(client);
|
2019-10-22 21:46:50 +00:00
|
|
|
|
2020-03-08 18:57:59 +00:00
|
|
|
while let Some(events) = agent.wait_for_events().await {
|
|
|
|
assert!(match events[0] {
|
2023-12-11 12:48:39 +00:00
|
|
|
Event::Disconnected(_) => true,
|
2020-03-08 18:57:59 +00:00
|
|
|
_ => false,
|
|
|
|
});
|
|
|
|
assert_eq!(events.len(), 1);
|
|
|
|
break;
|
|
|
|
}
|
2019-10-22 21:46:50 +00:00
|
|
|
}
|
|
|
|
}
|