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::str::FromStr;
10use std::rc::Rc;
11use std::cell::RefCell;
12use std::convert::TryFrom;
13use futures::{Future,Stream, Sink, sync::mpsc};
14use tokio_xmpp::{
15 Client as TokioXmppClient,
16 Event as TokioXmppEvent,
17 Packet,
18};
19use xmpp_parsers::{
20 bookmarks2::Conference,
21 caps::{compute_disco, hash_caps, Caps},
22 disco::{DiscoInfoQuery, DiscoInfoResult, Feature, Identity},
23 hashes::Algo,
24 iq::{Iq, IqType},
25 message::{Message, MessageType, Body},
26 muc::{
27 Muc,
28 user::{MucUser, Status},
29 },
30 ns,
31 presence::{Presence, Type as PresenceType},
32 pubsub::pubsub::{PubSub, Items},
33 roster::{Roster, Item as RosterItem},
34 stanza_error::{StanzaError, ErrorType, DefinedCondition},
35 Jid, BareJid, FullJid, JidParseError,
36};
37
38mod pubsub;
39
40pub type Error = tokio_xmpp::Error;
41
42#[derive(Debug)]
43pub enum ClientType {
44 Bot,
45 Pc,
46}
47
48impl Default for ClientType {
49 fn default() -> Self {
50 ClientType::Bot
51 }
52}
53
54impl ToString for ClientType {
55 fn to_string(&self) -> String {
56 String::from(
57 match self {
58 ClientType::Bot => "bot",
59 ClientType::Pc => "pc",
60 }
61 )
62 }
63}
64
65#[derive(PartialEq)]
66pub enum ClientFeature {
67 #[cfg(feature = "avatars")]
68 Avatars,
69 ContactList,
70 JoinRooms,
71}
72
73#[derive(Debug)]
74pub enum Event {
75 Online,
76 Disconnected,
77 ContactAdded(RosterItem),
78 ContactRemoved(RosterItem),
79 ContactChanged(RosterItem),
80 #[cfg(feature = "avatars")]
81 AvatarRetrieved(Jid, String),
82 JoinRoom(BareJid, Conference),
83 LeaveRoom(BareJid),
84 LeaveAllRooms,
85 RoomJoined(BareJid),
86 RoomLeft(BareJid),
87}
88
89#[derive(Default)]
90pub struct ClientBuilder<'a> {
91 jid: &'a str,
92 password: &'a str,
93 website: String,
94 default_nick: String,
95 disco: (ClientType, String),
96 features: Vec<ClientFeature>,
97}
98
99impl ClientBuilder<'_> {
100 pub fn new<'a>(jid: &'a str, password: &'a str) -> ClientBuilder<'a> {
101 ClientBuilder {
102 jid,
103 password,
104 website: String::from("https://gitlab.com/xmpp-rs/tokio-xmpp"),
105 default_nick: String::from("xmpp-rs"),
106 disco: (ClientType::default(), String::from("tokio-xmpp")),
107 features: vec![],
108 }
109 }
110
111 pub fn set_client(mut self, type_: ClientType, name: &str) -> Self {
112 self.disco = (type_, String::from(name));
113 self
114 }
115
116 pub fn set_website(mut self, url: &str) -> Self {
117 self.website = String::from(url);
118 self
119 }
120
121 pub fn set_default_nick(mut self, nick: &str) -> Self {
122 self.default_nick = String::from(nick);
123 self
124 }
125
126 pub fn enable_feature(mut self, feature: ClientFeature) -> Self {
127 self.features.push(feature);
128 self
129 }
130
131 fn make_disco(&self) -> DiscoInfoResult {
132 let identities = vec![Identity::new("client", self.disco.0.to_string(),
133 "en", self.disco.1.to_string())];
134 let mut features = vec![
135 Feature::new(ns::DISCO_INFO),
136 ];
137 #[cfg(feature = "avatars")]
138 {
139 if self.features.contains(&ClientFeature::Avatars) {
140 features.push(Feature::new(format!("{}+notify", ns::AVATAR_METADATA)));
141 }
142 }
143 if self.features.contains(&ClientFeature::JoinRooms) {
144 features.push(Feature::new(format!("{}+notify", ns::BOOKMARKS2)));
145 }
146 DiscoInfoResult {
147 node: None,
148 identities,
149 features,
150 extensions: vec![],
151 }
152 }
153
154 fn make_initial_presence(disco: &DiscoInfoResult, node: &str) -> Presence {
155 let caps_data = compute_disco(disco);
156 let hash = hash_caps(&caps_data, Algo::Sha_1).unwrap();
157 let caps = Caps::new(node, hash);
158
159 let mut presence = Presence::new(PresenceType::None);
160 presence.add_payload(caps);
161 presence
162 }
163
164 pub fn build(
165 self,
166 ) -> Result<(Agent, impl Stream<Item = Event, Error = tokio_xmpp::Error>), JidParseError> {
167 let client = TokioXmppClient::new(self.jid, self.password)?;
168 Ok(self.build_impl(client))
169 }
170
171 // This function is meant to be used for testing build
172 pub(crate) fn build_impl<S>(
173 self,
174 stream: S,
175 ) -> (Agent, impl Stream<Item = Event, Error = tokio_xmpp::Error>)
176 where
177 S: Stream<Item = tokio_xmpp::Event, Error = tokio_xmpp::Error>
178 + Sink<SinkItem = tokio_xmpp::Packet, SinkError = tokio_xmpp::Error>,
179 {
180 let disco = self.make_disco();
181 let node = self.website;
182 let (sender_tx, sender_rx) = mpsc::unbounded();
183
184 let client = stream;
185 let (sink, stream) = client.split();
186
187 let reader = {
188 let mut sender_tx = sender_tx.clone();
189 let jid = self.jid.to_owned();
190 stream.map(move |event| {
191 // Helper function to send an iq error.
192 let mut events = Vec::new();
193 let send_error = |to, id, type_, condition, text: &str| {
194 let error = StanzaError::new(type_, condition, "en", text);
195 let iq = Iq::from_error(id, error)
196 .with_to(to)
197 .into();
198 sender_tx.unbounded_send(Packet::Stanza(iq)).unwrap();
199 };
200
201 match event {
202 TokioXmppEvent::Online => {
203 let presence = ClientBuilder::make_initial_presence(&disco, &node).into();
204 let packet = Packet::Stanza(presence);
205 sender_tx.unbounded_send(packet)
206 .unwrap();
207 events.push(Event::Online);
208 // TODO: only send this when the ContactList feature is enabled.
209 let iq = Iq::from_get("roster", Roster { ver: None, items: vec![] })
210 .into();
211 sender_tx.unbounded_send(Packet::Stanza(iq)).unwrap();
212 // TODO: only send this when the JoinRooms feature is enabled.
213 let iq = Iq::from_get("bookmarks", PubSub::Items(Items::new(ns::BOOKMARKS2)))
214 .into();
215 sender_tx.unbounded_send(Packet::Stanza(iq)).unwrap();
216 }
217 TokioXmppEvent::Disconnected => {
218 events.push(Event::Disconnected);
219 }
220 TokioXmppEvent::Stanza(stanza) => {
221 if stanza.is("iq", "jabber:client") {
222 let iq = Iq::try_from(stanza).unwrap();
223 let from =
224 iq.from.clone().unwrap_or_else(|| Jid::from_str(&jid).unwrap());
225 if let IqType::Get(payload) = iq.payload {
226 if payload.is("query", ns::DISCO_INFO) {
227 let query = DiscoInfoQuery::try_from(payload);
228 match query {
229 Ok(query) => {
230 let mut disco_info = disco.clone();
231 disco_info.node = query.node;
232 let iq = Iq::from_result(iq.id, Some(disco_info))
233 .with_to(iq.from.unwrap())
234 .into();
235 sender_tx.unbounded_send(Packet::Stanza(iq)).unwrap();
236 },
237 Err(err) => {
238 send_error(iq.from.unwrap(), iq.id, ErrorType::Modify, DefinedCondition::BadRequest, &format!("{}", err));
239 },
240 }
241 } else {
242 // We MUST answer unhandled get iqs with a service-unavailable error.
243 send_error(iq.from.unwrap(), iq.id, ErrorType::Cancel, DefinedCondition::ServiceUnavailable, "No handler defined for this kind of iq.");
244 }
245 } else if let IqType::Result(Some(payload)) = iq.payload {
246 // TODO: move private iqs like this one somewhere else, for
247 // security reasons.
248 if payload.is("query", ns::ROSTER) && iq.from.is_none() {
249 let roster = Roster::try_from(payload).unwrap();
250 for item in roster.items.into_iter() {
251 events.push(Event::ContactAdded(item));
252 }
253 } else if payload.is("pubsub", ns::PUBSUB) {
254 let new_events = pubsub::handle_iq_result(&from, payload);
255 events.extend(new_events);
256 }
257 } else if let IqType::Set(_) = iq.payload {
258 // We MUST answer unhandled set iqs with a service-unavailable error.
259 send_error(iq.from.unwrap(), iq.id, ErrorType::Cancel, DefinedCondition::ServiceUnavailable, "No handler defined for this kind of iq.");
260 }
261 } else if stanza.is("message", "jabber:client") {
262 let message = Message::try_from(stanza).unwrap();
263 let from = message.from.clone().unwrap();
264 for child in message.payloads {
265 if child.is("event", ns::PUBSUB_EVENT) {
266 let new_events = pubsub::handle_event(&from, child, &mut sender_tx);
267 events.extend(new_events);
268 }
269 }
270 } else if stanza.is("presence", "jabber:client") {
271 let presence = Presence::try_from(stanza).unwrap();
272 let from: BareJid = match presence.from.clone().unwrap() {
273 Jid::Full(FullJid { node, domain, .. }) => BareJid { node, domain },
274 Jid::Bare(bare) => bare,
275 };
276 for payload in presence.payloads.into_iter() {
277 let muc_user = match MucUser::try_from(payload) {
278 Ok(muc_user) => muc_user,
279 _ => continue
280 };
281 for status in muc_user.status.into_iter() {
282 if status == Status::SelfPresence {
283 events.push(Event::RoomJoined(from.clone()));
284 break;
285 }
286 }
287 }
288 } else if stanza.is("error", "http://etherx.jabber.org/streams") {
289 println!("Received a fatal stream error: {}", String::from(&stanza));
290 } else {
291 panic!("Unknown stanza: {}", String::from(&stanza));
292 }
293 }
294 }
295
296 futures::stream::iter_ok(events)
297 })
298 .flatten()
299 };
300
301 let sender = sender_rx
302 .map_err(|e| panic!("Sink error: {:?}", e))
303 .forward(sink)
304 .map(|(rx, mut sink)| {
305 drop(rx);
306 let _ = sink.close();
307 None
308 });
309
310 // TODO is this correct?
311 // Some(Error) means a real error
312 // None means the end of the sender stream and can be ignored
313 let future = reader
314 .map(Some)
315 .select(sender.into_stream())
316 .filter_map(|x| x);
317
318 let agent = Agent {
319 sender_tx,
320 default_nick: Rc::new(RefCell::new(self.default_nick)),
321 };
322
323 (agent, future)
324 }
325}
326
327#[derive(Clone)]
328pub struct Agent {
329 sender_tx: mpsc::UnboundedSender<Packet>,
330 default_nick: Rc<RefCell<String>>,
331}
332
333impl Agent {
334 pub fn join_room(&mut self, room: BareJid, nick: Option<String>, password: Option<String>,
335 lang: &str, status: &str) {
336 let mut muc = Muc::new();
337 if let Some(password) = password {
338 muc = muc.with_password(password);
339 }
340
341 let nick = nick.unwrap_or_else(|| self.default_nick.borrow().clone());
342 let room_jid = room.with_resource(nick);
343 let mut presence = Presence::new(PresenceType::None)
344 .with_to(Jid::Full(room_jid));
345 presence.add_payload(muc);
346 presence.set_status(String::from(lang), String::from(status));
347 let presence = presence.into();
348 self.sender_tx.unbounded_send(Packet::Stanza(presence))
349 .unwrap();
350 }
351
352 pub fn send_message(&mut self, recipient: Jid, type_: MessageType, lang: &str, text: &str) {
353 let mut message = Message::new(Some(recipient));
354 message.type_ = type_;
355 message.bodies.insert(String::from(lang), Body(String::from(text)));
356 let message = message.into();
357 self.sender_tx.unbounded_send(Packet::Stanza(message))
358 .unwrap();
359 }
360}