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    disco::DiscoInfoResult,
 14    message::{Body, Message, MessageType},
 15};
 16use tokio_xmpp::AsyncClient as TokioXmppClient;
 17pub use tokio_xmpp::{BareJid, Element, FullJid, Jid};
 18#[macro_use]
 19extern crate log;
 20
 21pub mod builder;
 22pub mod disco;
 23pub mod event;
 24pub mod event_loop;
 25pub mod feature;
 26pub mod iq;
 27pub mod message;
 28pub mod muc;
 29pub mod presence;
 30pub mod pubsub;
 31pub mod upload;
 32
 33// Module re-exports
 34pub use builder::{ClientBuilder, ClientType};
 35pub use event::Event;
 36pub use feature::ClientFeature;
 37
 38pub type Error = tokio_xmpp::Error;
 39pub type Id = Option<String>;
 40pub type RoomNick = String;
 41
 42pub struct Agent {
 43    client: TokioXmppClient,
 44    default_nick: Arc<RwLock<String>>,
 45    lang: Arc<Vec<String>>,
 46    disco: DiscoInfoResult,
 47    node: String,
 48    uploads: Vec<(String, Jid, PathBuf)>,
 49    awaiting_disco_bookmarks_type: bool,
 50}
 51
 52impl Agent {
 53    pub async fn disconnect(&mut self) -> Result<(), Error> {
 54        self.client.send_end().await
 55    }
 56
 57    pub async fn join_room(
 58        &mut self,
 59        room: BareJid,
 60        nick: Option<String>,
 61        password: Option<String>,
 62        lang: &str,
 63        status: &str,
 64    ) {
 65        muc::room::join_room(self, room, nick, password, lang, status).await
 66    }
 67
 68    /// Send a "leave room" request to the server (specifically, an "unavailable" presence stanza).
 69    ///
 70    /// The returned future will resolve when the request has been sent,
 71    /// not when the room has actually been left.
 72    ///
 73    /// If successful, a `RoomLeft` event should be received later as a confirmation.
 74    ///
 75    /// See: https://xmpp.org/extensions/xep-0045.html#exit
 76    ///
 77    /// Note that this method does NOT remove the room from the auto-join list; the latter
 78    /// is more a list of bookmarks that the account knows about and that have a flag set
 79    /// to indicate that they should be joined automatically after connecting (see the JoinRoom event).
 80    ///
 81    /// Regarding the latter, see the these minutes about auto-join behavior:
 82    /// https://docs.modernxmpp.org/meetings/2019-01-brussels/#bookmarks
 83    ///
 84    /// # Arguments
 85    ///
 86    /// * `room_jid`: The JID of the room to leave.
 87    /// * `nickname`: The nickname to use in the room.
 88    /// * `lang`: The language of the status message.
 89    /// * `status`: The status message to send.
 90    pub async fn leave_room(
 91        &mut self,
 92        room_jid: BareJid,
 93        nickname: RoomNick,
 94        lang: impl Into<String>,
 95        status: impl Into<String>,
 96    ) {
 97        muc::room::leave_room(self, room_jid, nickname, lang, status).await
 98    }
 99
100    pub async fn send_message(
101        &mut self,
102        recipient: Jid,
103        type_: MessageType,
104        lang: &str,
105        text: &str,
106    ) {
107        let mut message = Message::new(Some(recipient));
108        message.type_ = type_;
109        message
110            .bodies
111            .insert(String::from(lang), Body(String::from(text)));
112        let _ = self.client.send_stanza(message.into()).await;
113    }
114
115    pub async fn send_room_private_message(
116        &mut self,
117        room: BareJid,
118        recipient: RoomNick,
119        lang: &str,
120        text: &str,
121    ) {
122        muc::private_message::send_room_private_message(self, room, recipient, lang, text).await
123    }
124
125    /// Wait for new events.
126    ///
127    /// # Returns
128    ///
129    /// - `Some(events)` if there are new events; multiple may be returned at once.
130    /// - `None` if the underlying stream is closed.
131    pub async fn wait_for_events(&mut self) -> Option<Vec<Event>> {
132        event_loop::wait_for_events(self).await
133    }
134
135    pub async fn upload_file_with(&mut self, service: &str, path: &Path) {
136        upload::send::upload_file_with(self, service, path).await
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::{Agent, BareJid, ClientBuilder, ClientFeature, ClientType, Event};
143    use std::str::FromStr;
144    use tokio_xmpp::AsyncClient as TokioXmppClient;
145
146    #[tokio::test]
147    async fn test_simple() {
148        let jid = BareJid::from_str("foo@bar").unwrap();
149
150        let client = TokioXmppClient::new(jid.clone(), "meh");
151
152        // Client instance
153        let client_builder = ClientBuilder::new(jid, "meh")
154            .set_client(ClientType::Bot, "xmpp-rs")
155            .set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
156            .set_default_nick("bot")
157            .enable_feature(ClientFeature::ContactList);
158
159        #[cfg(feature = "avatars")]
160        let client_builder = client_builder.enable_feature(ClientFeature::Avatars);
161
162        let mut agent: Agent = client_builder.build_impl(client);
163
164        while let Some(events) = agent.wait_for_events().await {
165            assert!(match events[0] {
166                Event::Disconnected(_) => true,
167                _ => false,
168            });
169            assert_eq!(events.len(), 1);
170            break;
171        }
172    }
173}