listen for Presence and return MucPresence

Maxime “pep” Buquet created

Change summary

src/plugins/muc.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++---
1 file changed, 45 insertions(+), 4 deletions(-)

Detailed changes

src/plugins/muc.rs 🔗

@@ -1,12 +1,27 @@
 use std::collections::BTreeMap;
+use std::convert::TryFrom;
 
 use jid::Jid;
 use error::Error;
 use plugin::PluginProxy;
 
-pub use xmpp_parsers::muc::Muc;
+use event::{Event, Propagation, Priority};
+
+pub use xmpp_parsers::muc::{Muc, MucUser};
+pub use xmpp_parsers::muc::user::{Status, Affiliation, Role};
 pub use xmpp_parsers::presence::{Presence, Type, Show};
 
+#[derive(Debug)]
+pub struct MucPresence {
+    pub room: Jid,
+    pub nick: Option<String>,
+    pub to: Jid,
+    pub type_: Type,
+    pub x: MucUser,
+}
+
+impl Event for MucPresence {}
+
 pub struct MucPlugin {
     proxy: PluginProxy,
 }
@@ -19,6 +34,7 @@ impl MucPlugin {
     }
 
     pub fn join_room(&self, room: Jid) -> Result<(), Error> {
+        let x = Muc { password: None };
         let presence = Presence {
             from: None,
             to: Some(room),
@@ -27,7 +43,7 @@ impl MucPlugin {
             show: Show::None,
             priority: 0i8,
             statuses: BTreeMap::new(),
-            payloads: vec![Muc.into()],
+            payloads: vec![x.into()],
         };
         self.proxy.send(presence.into());
 
@@ -35,6 +51,7 @@ impl MucPlugin {
     }
 
     pub fn leave_room(&self, room: Jid) -> Result<(), Error> {
+        let x = Muc { password: None };
         let presence = Presence {
             from: None,
             to: Some(room),
@@ -43,11 +60,35 @@ impl MucPlugin {
             show: Show::None,
             priority: 0i8,
             statuses: BTreeMap::new(),
-            payloads: vec![Muc.into()],
+            payloads: vec![x.into()],
         };
         self.proxy.send(presence.into());
         Ok(())
     }
+
+    fn handle_presence(&self, presence: &Presence) -> Propagation {
+        let from = presence.from.clone().unwrap();
+        let room = from.clone().into_bare_jid();
+        let nick = from.resource;
+        let to = presence.to.clone().unwrap();
+        let type_ = presence.type_.clone();
+
+        for payload in presence.clone().payloads {
+            if let Ok(x) = MucUser::try_from(payload) {
+                self.proxy.dispatch(MucPresence {
+                    room: room.clone(),
+                    nick: nick.clone(),
+                    to: to.clone(),
+                    type_: type_.clone(),
+                    x
+                });
+            }
+        }
+
+        Propagation::Stop
+    }
 }
 
-impl_plugin!(MucPlugin, proxy, []);
+impl_plugin!(MucPlugin, proxy, [
+    (Presence, Priority::Default) => handle_presence,
+]);