lib.rs

  1// Copyright (c) 2019 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
  2//
  3// This Source Code Form is subject to the terms of the Mozilla Public
  4// License, v. 2.0. If a copy of the MPL was not distributed with this
  5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6
  7#![deny(bare_trait_objects)]
  8
  9use std::path::{Path, PathBuf};
 10use std::sync::{Arc, RwLock};
 11pub use tokio_xmpp::parsers;
 12use tokio_xmpp::parsers::{
 13    caps::{compute_disco, hash_caps, Caps},
 14    disco::DiscoInfoResult,
 15    hashes::Algo,
 16    message::{Body, Message, MessageType},
 17    muc::{user::MucUser, Muc},
 18    presence::{Presence, Type as PresenceType},
 19};
 20use tokio_xmpp::AsyncClient as TokioXmppClient;
 21pub use tokio_xmpp::{BareJid, Element, FullJid, Jid};
 22#[macro_use]
 23extern crate log;
 24
 25pub mod builder;
 26pub mod disco;
 27pub mod event;
 28pub mod event_loop;
 29pub mod feature;
 30pub mod iq;
 31pub mod message;
 32pub mod presence;
 33pub mod pubsub;
 34pub mod upload;
 35
 36// Module re-exports
 37pub use builder::{ClientBuilder, ClientType};
 38pub use event::Event;
 39pub use feature::ClientFeature;
 40
 41pub type Error = tokio_xmpp::Error;
 42pub type Id = Option<String>;
 43pub type RoomNick = String;
 44
 45pub struct Agent {
 46    client: TokioXmppClient,
 47    default_nick: Arc<RwLock<String>>,
 48    lang: Arc<Vec<String>>,
 49    disco: DiscoInfoResult,
 50    node: String,
 51    uploads: Vec<(String, Jid, PathBuf)>,
 52    awaiting_disco_bookmarks_type: bool,
 53}
 54
 55impl Agent {
 56    pub async fn disconnect(&mut self) -> Result<(), Error> {
 57        self.client.send_end().await
 58    }
 59
 60    pub async fn join_room(
 61        &mut self,
 62        room: BareJid,
 63        nick: Option<String>,
 64        password: Option<String>,
 65        lang: &str,
 66        status: &str,
 67    ) {
 68        let mut muc = Muc::new();
 69        if let Some(password) = password {
 70            muc = muc.with_password(password);
 71        }
 72
 73        let nick = nick.unwrap_or_else(|| self.default_nick.read().unwrap().clone());
 74        let room_jid = room.with_resource_str(&nick).unwrap();
 75        let mut presence = Presence::new(PresenceType::None).with_to(room_jid);
 76        presence.add_payload(muc);
 77        presence.set_status(String::from(lang), String::from(status));
 78        let _ = self.client.send_stanza(presence.into()).await;
 79    }
 80
 81    /// Send a "leave room" request to the server (specifically, an "unavailable" presence stanza).
 82    ///
 83    /// The returned future will resolve when the request has been sent,
 84    /// not when the room has actually been left.
 85    ///
 86    /// If successful, a `RoomLeft` event should be received later as a confirmation.
 87    ///
 88    /// See: https://xmpp.org/extensions/xep-0045.html#exit
 89    ///
 90    /// Note that this method does NOT remove the room from the auto-join list; the latter
 91    /// is more a list of bookmarks that the account knows about and that have a flag set
 92    /// to indicate that they should be joined automatically after connecting (see the JoinRoom event).
 93    ///
 94    /// Regarding the latter, see the these minutes about auto-join behavior:
 95    /// https://docs.modernxmpp.org/meetings/2019-01-brussels/#bookmarks
 96    ///
 97    /// # Arguments
 98    ///
 99    /// * `room_jid`: The JID of the room to leave.
100    /// * `nickname`: The nickname to use in the room.
101    /// * `lang`: The language of the status message.
102    /// * `status`: The status message to send.
103    pub async fn leave_room(
104        &mut self,
105        room_jid: BareJid,
106        nickname: RoomNick,
107        lang: impl Into<String>,
108        status: impl Into<String>,
109    ) {
110        // XEP-0045 specifies that, to leave a room, the client must send a presence stanza
111        // with type="unavailable".
112        let mut presence = Presence::new(PresenceType::Unavailable).with_to(
113            room_jid
114                .with_resource_str(nickname.as_str())
115                .expect("Invalid room JID after adding resource part."),
116        );
117
118        // Optionally, the client may include a status message in the presence stanza.
119        // TODO: Should this be optional? The XEP says "MAY", but the method signature requires the arguments.
120        // XEP-0045: "The occupant MAY include normal <status/> information in the unavailable presence stanzas"
121        presence.set_status(lang, status);
122
123        // Send the presence stanza.
124        if let Err(e) = self.client.send_stanza(presence.into()).await {
125            // Report any errors to the log.
126            error!("Failed to send leave room presence: {}", e);
127        }
128    }
129
130    pub async fn send_message(
131        &mut self,
132        recipient: Jid,
133        type_: MessageType,
134        lang: &str,
135        text: &str,
136    ) {
137        let mut message = Message::new(Some(recipient));
138        message.type_ = type_;
139        message
140            .bodies
141            .insert(String::from(lang), Body(String::from(text)));
142        let _ = self.client.send_stanza(message.into()).await;
143    }
144
145    pub async fn send_room_private_message(
146        &mut self,
147        room: BareJid,
148        recipient: RoomNick,
149        lang: &str,
150        text: &str,
151    ) {
152        let recipient: Jid = room.with_resource_str(&recipient).unwrap().into();
153        let mut message = Message::new(recipient).with_payload(MucUser::new());
154        message.type_ = MessageType::Chat;
155        message
156            .bodies
157            .insert(String::from(lang), Body(String::from(text)));
158        let _ = self.client.send_stanza(message.into()).await;
159    }
160
161    fn make_initial_presence(disco: &DiscoInfoResult, node: &str) -> Presence {
162        let caps_data = compute_disco(disco);
163        let hash = hash_caps(&caps_data, Algo::Sha_1).unwrap();
164        let caps = Caps::new(node, hash);
165
166        let mut presence = Presence::new(PresenceType::None);
167        presence.add_payload(caps);
168        presence
169    }
170
171    /// Wait for new events.
172    ///
173    /// # Returns
174    ///
175    /// - `Some(events)` if there are new events; multiple may be returned at once.
176    /// - `None` if the underlying stream is closed.
177    pub async fn wait_for_events(&mut self) -> Option<Vec<Event>> {
178        event_loop::wait_for_events(self).await
179    }
180
181    pub async fn upload_file_with(&mut self, service: &str, path: &Path) {
182        upload::send::upload_file_with(self, service, path).await
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::{Agent, BareJid, ClientBuilder, ClientFeature, ClientType, Event};
189    use std::str::FromStr;
190    use tokio_xmpp::AsyncClient as TokioXmppClient;
191
192    #[tokio::test]
193    async fn test_simple() {
194        let jid = BareJid::from_str("foo@bar").unwrap();
195
196        let client = TokioXmppClient::new(jid.clone(), "meh");
197
198        // Client instance
199        let client_builder = ClientBuilder::new(jid, "meh")
200            .set_client(ClientType::Bot, "xmpp-rs")
201            .set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
202            .set_default_nick("bot")
203            .enable_feature(ClientFeature::ContactList);
204
205        #[cfg(feature = "avatars")]
206        let client_builder = client_builder.enable_feature(ClientFeature::Avatars);
207
208        let mut agent: Agent = client_builder.build_impl(client);
209
210        while let Some(events) = agent.wait_for_events().await {
211            assert!(match events[0] {
212                Event::Disconnected(_) => true,
213                _ => false,
214            });
215            assert_eq!(events.len(), 1);
216            break;
217        }
218    }
219}