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 alloc::sync::Arc;
8use std::collections::HashMap;
9use std::path::{Path, PathBuf};
10use tokio::sync::RwLock;
11
12use crate::{
13 event_loop,
14 jid::{BareJid, Jid},
15 message, muc,
16 parsers::disco::DiscoInfoResult,
17 upload, Error, Event, RoomNick,
18};
19use tokio_xmpp::Client as TokioXmppClient;
20
21pub struct Agent {
22 pub(crate) client: TokioXmppClient,
23 pub(crate) default_nick: Arc<RwLock<RoomNick>>,
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, RoomNick>,
31 pub(crate) rooms_joining: HashMap<BareJid, RoomNick>,
32 pub(crate) rooms_leaving: HashMap<BareJid, RoomNick>,
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_raw_message<'a>(&mut self, settings: message::send::RawMessageSettings<'a>) {
53 message::send::send_raw_message(self, settings).await
54 }
55
56 pub async fn send_message<'a>(&mut self, settings: message::send::MessageSettings<'a>) {
57 message::send::send_message(self, settings).await
58 }
59
60 pub async fn send_room_message<'a>(&mut self, settings: muc::room::RoomMessageSettings<'a>) {
61 muc::room::send_room_message(self, settings).await
62 }
63
64 pub async fn send_room_private_message<'a>(
65 &mut self,
66 settings: muc::private_message::RoomPrivateMessageSettings<'a>,
67 ) {
68 muc::private_message::send_room_private_message(self, settings).await
69 }
70
71 /// Wait for new events, or Error::Disconnected when connection is closed and will not reconnect.
72 pub async fn wait_for_events(&mut self) -> Vec<Event> {
73 event_loop::wait_for_events(self).await
74 }
75
76 pub async fn upload_file_with(&mut self, service: &str, path: &Path) {
77 upload::send::upload_file_with(self, service, path).await
78 }
79
80 /// Get the bound jid of the client.
81 ///
82 /// If the client is not connected, this will be None.
83 pub fn bound_jid(&self) -> Option<&Jid> {
84 self.client.bound_jid()
85 }
86}