1// Copyright (c) 2023 xmpp-rs contributors.
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
7use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use tokio::sync::RwLock;
11pub use tokio_xmpp::parsers;
12use tokio_xmpp::parsers::{disco::DiscoInfoResult, message::MessageType};
13pub use tokio_xmpp::{
14 jid::{BareJid, FullJid, Jid},
15 minidom::Element,
16 Client as TokioXmppClient,
17};
18
19use crate::{event_loop, message, muc, upload, Error, Event, RoomNick};
20
21pub struct Agent {
22 pub(crate) client: TokioXmppClient,
23 pub(crate) default_nick: Arc<RwLock<String>>,
24 pub(crate) lang: Arc<Vec<String>>,
25 pub(crate) disco: DiscoInfoResult,
26 pub(crate) node: String,
27 pub(crate) uploads: Vec<(String, Jid, PathBuf)>,
28 pub(crate) awaiting_disco_bookmarks_type: bool,
29 // Mapping of room->nick
30 pub(crate) rooms_joined: HashMap<BareJid, String>,
31 pub(crate) rooms_joining: HashMap<BareJid, String>,
32 pub(crate) rooms_leaving: HashMap<BareJid, String>,
33}
34
35impl Agent {
36 pub async fn disconnect(self) -> Result<(), Error> {
37 self.client.send_end().await
38 }
39
40 pub async fn join_room<'a>(&mut self, settings: muc::room::JoinRoomSettings<'a>) {
41 muc::room::join_room(self, settings).await
42 }
43
44 /// Request to leave a chatroom.
45 ///
46 /// If successful, an [Event::RoomLeft] event will be produced. This method does not remove the room
47 /// from bookmarks nor remove the autojoin flag. See [muc::room::leave_room] for more information.
48 pub async fn leave_room<'a>(&mut self, settings: muc::room::LeaveRoomSettings<'a>) {
49 muc::room::leave_room(self, settings).await
50 }
51
52 pub async fn send_message(
53 &mut self,
54 recipient: Jid,
55 type_: MessageType,
56 lang: &str,
57 text: &str,
58 ) {
59 message::send::send_message(self, recipient, type_, lang, text).await
60 }
61
62 pub async fn send_room_message<'a>(&mut self, settings: muc::room::RoomMessageSettings<'a>) {
63 muc::room::send_room_message(self, settings).await
64 }
65
66 pub async fn send_room_private_message(
67 &mut self,
68 room: BareJid,
69 recipient: RoomNick,
70 lang: &str,
71 text: &str,
72 ) {
73 muc::private_message::send_room_private_message(self, room, recipient, lang, text).await
74 }
75
76 /// Wait for new events, or Error::Disconnected when connection is closed and will not reconnect.
77 pub async fn wait_for_events(&mut self) -> Vec<Event> {
78 event_loop::wait_for_events(self).await
79 }
80
81 pub async fn upload_file_with(&mut self, service: &str, path: &Path) {
82 upload::send::upload_file_with(self, service, path).await
83 }
84
85 /// Get the bound jid of the client.
86 ///
87 /// If the client is not connected, this will be None.
88 pub fn bound_jid(&self) -> Option<&Jid> {
89 self.client.bound_jid()
90 }
91}