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 futures::stream::StreamExt;
10use std::path::{Path, PathBuf};
11use std::sync::{Arc, RwLock};
12use tokio::fs::File;
13pub use tokio_xmpp::parsers;
14use tokio_xmpp::parsers::{
15 bookmarks, bookmarks2,
16 caps::{compute_disco, hash_caps, Caps},
17 disco::{DiscoInfoQuery, DiscoInfoResult, Feature},
18 hashes::Algo,
19 http_upload::SlotRequest,
20 iq::Iq,
21 message::{Body, Message, MessageType},
22 muc::{user::MucUser, Muc},
23 ns,
24 presence::{Presence, Type as PresenceType},
25 private::Query as PrivateXMLQuery,
26 pubsub::pubsub::{Items, PubSub},
27 roster::{Item as RosterItem, Roster},
28 Error as ParsersError,
29};
30use tokio_xmpp::{AsyncClient as TokioXmppClient, Event as TokioXmppEvent};
31pub use tokio_xmpp::{BareJid, Element, FullJid, Jid};
32#[macro_use]
33extern crate log;
34
35pub mod builder;
36pub mod feature;
37pub mod iq;
38pub mod message;
39pub mod presence;
40pub mod pubsub;
41pub mod upload;
42
43// Module re-exports
44pub use builder::{ClientBuilder, ClientType};
45pub use feature::ClientFeature;
46
47pub type Error = tokio_xmpp::Error;
48pub type Id = Option<String>;
49pub type RoomNick = String;
50
51#[derive(Debug)]
52pub enum Event {
53 Online,
54 Disconnected(Error),
55 ContactAdded(RosterItem),
56 ContactRemoved(RosterItem),
57 ContactChanged(RosterItem),
58 #[cfg(feature = "avatars")]
59 AvatarRetrieved(Jid, String),
60 ChatMessage(Id, BareJid, Body),
61 JoinRoom(BareJid, bookmarks2::Conference),
62 LeaveRoom(BareJid),
63 LeaveAllRooms,
64 RoomJoined(BareJid),
65 RoomLeft(BareJid),
66 RoomMessage(Id, BareJid, RoomNick, Body),
67 /// A private message received from a room, containing the message ID, the room's BareJid,
68 /// the sender's nickname, and the message body.
69 RoomPrivateMessage(Id, BareJid, RoomNick, Body),
70 ServiceMessage(Id, BareJid, Body),
71 HttpUploadedFile(String),
72}
73
74pub struct Agent {
75 client: TokioXmppClient,
76 default_nick: Arc<RwLock<String>>,
77 lang: Arc<Vec<String>>,
78 disco: DiscoInfoResult,
79 node: String,
80 uploads: Vec<(String, Jid, PathBuf)>,
81 awaiting_disco_bookmarks_type: bool,
82}
83
84impl Agent {
85 pub async fn disconnect(&mut self) -> Result<(), Error> {
86 self.client.send_end().await
87 }
88
89 pub async fn join_room(
90 &mut self,
91 room: BareJid,
92 nick: Option<String>,
93 password: Option<String>,
94 lang: &str,
95 status: &str,
96 ) {
97 let mut muc = Muc::new();
98 if let Some(password) = password {
99 muc = muc.with_password(password);
100 }
101
102 let nick = nick.unwrap_or_else(|| self.default_nick.read().unwrap().clone());
103 let room_jid = room.with_resource_str(&nick).unwrap();
104 let mut presence = Presence::new(PresenceType::None).with_to(room_jid);
105 presence.add_payload(muc);
106 presence.set_status(String::from(lang), String::from(status));
107 let _ = self.client.send_stanza(presence.into()).await;
108 }
109
110 /// Send a "leave room" request to the server (specifically, an "unavailable" presence stanza).
111 ///
112 /// The returned future will resolve when the request has been sent,
113 /// not when the room has actually been left.
114 ///
115 /// If successful, a `RoomLeft` event should be received later as a confirmation.
116 ///
117 /// See: https://xmpp.org/extensions/xep-0045.html#exit
118 ///
119 /// Note that this method does NOT remove the room from the auto-join list; the latter
120 /// is more a list of bookmarks that the account knows about and that have a flag set
121 /// to indicate that they should be joined automatically after connecting (see the JoinRoom event).
122 ///
123 /// Regarding the latter, see the these minutes about auto-join behavior:
124 /// https://docs.modernxmpp.org/meetings/2019-01-brussels/#bookmarks
125 ///
126 /// # Arguments
127 ///
128 /// * `room_jid`: The JID of the room to leave.
129 /// * `nickname`: The nickname to use in the room.
130 /// * `lang`: The language of the status message.
131 /// * `status`: The status message to send.
132 pub async fn leave_room(
133 &mut self,
134 room_jid: BareJid,
135 nickname: RoomNick,
136 lang: impl Into<String>,
137 status: impl Into<String>,
138 ) {
139 // XEP-0045 specifies that, to leave a room, the client must send a presence stanza
140 // with type="unavailable".
141 let mut presence = Presence::new(PresenceType::Unavailable).with_to(
142 room_jid
143 .with_resource_str(nickname.as_str())
144 .expect("Invalid room JID after adding resource part."),
145 );
146
147 // Optionally, the client may include a status message in the presence stanza.
148 // TODO: Should this be optional? The XEP says "MAY", but the method signature requires the arguments.
149 // XEP-0045: "The occupant MAY include normal <status/> information in the unavailable presence stanzas"
150 presence.set_status(lang, status);
151
152 // Send the presence stanza.
153 if let Err(e) = self.client.send_stanza(presence.into()).await {
154 // Report any errors to the log.
155 error!("Failed to send leave room presence: {}", e);
156 }
157 }
158
159 pub async fn send_message(
160 &mut self,
161 recipient: Jid,
162 type_: MessageType,
163 lang: &str,
164 text: &str,
165 ) {
166 let mut message = Message::new(Some(recipient));
167 message.type_ = type_;
168 message
169 .bodies
170 .insert(String::from(lang), Body(String::from(text)));
171 let _ = self.client.send_stanza(message.into()).await;
172 }
173
174 pub async fn send_room_private_message(
175 &mut self,
176 room: BareJid,
177 recipient: RoomNick,
178 lang: &str,
179 text: &str,
180 ) {
181 let recipient: Jid = room.with_resource_str(&recipient).unwrap().into();
182 let mut message = Message::new(recipient).with_payload(MucUser::new());
183 message.type_ = MessageType::Chat;
184 message
185 .bodies
186 .insert(String::from(lang), Body(String::from(text)));
187 let _ = self.client.send_stanza(message.into()).await;
188 }
189
190 fn make_initial_presence(disco: &DiscoInfoResult, node: &str) -> Presence {
191 let caps_data = compute_disco(disco);
192 let hash = hash_caps(&caps_data, Algo::Sha_1).unwrap();
193 let caps = Caps::new(node, hash);
194
195 let mut presence = Presence::new(PresenceType::None);
196 presence.add_payload(caps);
197 presence
198 }
199
200 // This method is a workaround due to prosody bug https://issues.prosody.im/1664
201 // FIXME: To be removed in the future
202 // The server doesn't return disco#info feature when querying the account
203 // so we add it manually because we know it's true
204 async fn handle_disco_info_result_payload(&mut self, payload: Element, from: Jid) {
205 match DiscoInfoResult::try_from(payload.clone()) {
206 Ok(disco) => {
207 self.handle_disco_info_result(disco, from).await;
208 }
209 Err(e) => match e {
210 ParsersError::ParseError(reason) => {
211 if reason == "disco#info feature not present in disco#info." {
212 let mut payload = payload.clone();
213 let disco_feature =
214 Feature::new("http://jabber.org/protocol/disco#info").into();
215 payload.append_child(disco_feature);
216 match DiscoInfoResult::try_from(payload) {
217 Ok(disco) => {
218 self.handle_disco_info_result(disco, from).await;
219 }
220 Err(e) => {
221 panic!("Wrong disco#info format after workaround: {}", e)
222 }
223 }
224 } else {
225 panic!(
226 "Wrong disco#info format (reason cannot be worked around): {}",
227 e
228 )
229 }
230 }
231 _ => panic!("Wrong disco#info format: {}", e),
232 },
233 }
234 }
235
236 async fn handle_disco_info_result(&mut self, disco: DiscoInfoResult, from: Jid) {
237 // Safe unwrap because no DISCO is received when we are not online
238 if from == self.client.bound_jid().unwrap().to_bare() && self.awaiting_disco_bookmarks_type
239 {
240 info!("Received disco info about bookmarks type");
241 // Trigger bookmarks query
242 // TODO: only send this when the JoinRooms feature is enabled.
243 self.awaiting_disco_bookmarks_type = false;
244 let mut perform_bookmarks2 = false;
245 info!("{:#?}", disco.features);
246 for feature in disco.features {
247 if feature.var == "urn:xmpp:bookmarks:1#compat" {
248 perform_bookmarks2 = true;
249 }
250 }
251
252 if perform_bookmarks2 {
253 // XEP-0402 bookmarks (modern)
254 let iq =
255 Iq::from_get("bookmarks", PubSub::Items(Items::new(ns::BOOKMARKS2))).into();
256 let _ = self.client.send_stanza(iq).await;
257 } else {
258 // XEP-0048 v1.0 bookmarks (legacy)
259 let iq = Iq::from_get(
260 "bookmarks-legacy",
261 PrivateXMLQuery {
262 storage: bookmarks::Storage::new(),
263 },
264 )
265 .into();
266 let _ = self.client.send_stanza(iq).await;
267 }
268 } else {
269 unimplemented!("Ignored disco#info response from {}", from);
270 }
271 }
272
273 /// Wait for new events.
274 ///
275 /// # Returns
276 ///
277 /// - `Some(events)` if there are new events; multiple may be returned at once.
278 /// - `None` if the underlying stream is closed.
279 pub async fn wait_for_events(&mut self) -> Option<Vec<Event>> {
280 if let Some(event) = self.client.next().await {
281 let mut events = Vec::new();
282
283 match event {
284 TokioXmppEvent::Online { resumed: false, .. } => {
285 let presence = Self::make_initial_presence(&self.disco, &self.node).into();
286 let _ = self.client.send_stanza(presence).await;
287 events.push(Event::Online);
288 // TODO: only send this when the ContactList feature is enabled.
289 let iq = Iq::from_get(
290 "roster",
291 Roster {
292 ver: None,
293 items: vec![],
294 },
295 )
296 .into();
297 let _ = self.client.send_stanza(iq).await;
298
299 // Query account disco to know what bookmarks spec is used
300 let iq = Iq::from_get("disco-account", DiscoInfoQuery { node: None }).into();
301 let _ = self.client.send_stanza(iq).await;
302 self.awaiting_disco_bookmarks_type = true;
303 }
304 TokioXmppEvent::Online { resumed: true, .. } => {}
305 TokioXmppEvent::Disconnected(e) => {
306 events.push(Event::Disconnected(e));
307 }
308 TokioXmppEvent::Stanza(elem) => {
309 if elem.is("iq", "jabber:client") {
310 let iq = Iq::try_from(elem).unwrap();
311 let new_events = iq::handle_iq(self, iq).await;
312 events.extend(new_events);
313 } else if elem.is("message", "jabber:client") {
314 let message = Message::try_from(elem).unwrap();
315 let new_events = message::handle_message(self, message).await;
316 events.extend(new_events);
317 } else if elem.is("presence", "jabber:client") {
318 let presence = Presence::try_from(elem).unwrap();
319 let new_events = presence::handle_presence(self, presence).await;
320 events.extend(new_events);
321 } else if elem.is("error", "http://etherx.jabber.org/streams") {
322 println!("Received a fatal stream error: {}", String::from(&elem));
323 } else {
324 panic!("Unknown stanza: {}", String::from(&elem));
325 }
326 }
327 }
328
329 Some(events)
330 } else {
331 None
332 }
333 }
334
335 pub async fn upload_file_with(&mut self, service: &str, path: &Path) {
336 let name = path.file_name().unwrap().to_str().unwrap().to_string();
337 let file = File::open(path).await.unwrap();
338 let size = file.metadata().await.unwrap().len();
339 let slot_request = SlotRequest {
340 filename: name,
341 size: size,
342 content_type: None,
343 };
344 let to = service.parse::<Jid>().unwrap();
345 let request = Iq::from_get("upload1", slot_request).with_to(to.clone());
346 self.uploads
347 .push((String::from("upload1"), to, path.to_path_buf()));
348 self.client.send_stanza(request.into()).await.unwrap();
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::{Agent, BareJid, ClientBuilder, ClientFeature, ClientType, Event};
355 use std::str::FromStr;
356 use tokio_xmpp::AsyncClient as TokioXmppClient;
357
358 #[tokio::test]
359 async fn test_simple() {
360 let jid = BareJid::from_str("foo@bar").unwrap();
361
362 let client = TokioXmppClient::new(jid.clone(), "meh");
363
364 // Client instance
365 let client_builder = ClientBuilder::new(jid, "meh")
366 .set_client(ClientType::Bot, "xmpp-rs")
367 .set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
368 .set_default_nick("bot")
369 .enable_feature(ClientFeature::ContactList);
370
371 #[cfg(feature = "avatars")]
372 let client_builder = client_builder.enable_feature(ClientFeature::Avatars);
373
374 let mut agent: Agent = client_builder.build_impl(client);
375
376 while let Some(events) = agent.wait_for_events().await {
377 assert!(match events[0] {
378 Event::Disconnected(_) => true,
379 _ => false,
380 });
381 assert_eq!(events.len(), 1);
382 break;
383 }
384 }
385}