changeset 1358:bf3f669a6052 frontends_multi_profiles

plugins XEP-0045, XEP-0249, parrot: use JID instead of unicode in many methods + class attributes
author souliane <souliane@mailoo.org>
date Wed, 11 Mar 2015 12:35:21 +0100
parents f296a54af386
children 83127a4c89ce
files src/plugins/plugin_exp_parrot.py src/plugins/plugin_xep_0045.py src/plugins/plugin_xep_0249.py
diffstat 3 files changed, 58 insertions(+), 56 deletions(-) [+]
line wrap: on
line diff
--- a/src/plugins/plugin_exp_parrot.py	Mon Mar 09 16:37:15 2015 +0100
+++ b/src/plugins/plugin_exp_parrot.py	Wed Mar 11 12:35:21 2015 +0100
@@ -91,7 +91,7 @@
                     entity_type = "contact"
                 if entity_type == 'chatroom':
                     src_txt = from_jid.resource
-                    if src_txt == self.host.plugins["XEP-0045"].getRoomNick(from_jid.userhost(), profile):
+                    if src_txt == self.host.plugins["XEP-0045"].getRoomNick(from_jid.userhostJID(), profile):
                         #we won't repeat our own messages
                         return True
                 else:
--- a/src/plugins/plugin_xep_0045.py	Mon Mar 09 16:37:15 2015 +0100
+++ b/src/plugins/plugin_xep_0045.py	Wed Mar 11 12:35:21 2015 +0100
@@ -117,7 +117,7 @@
         profile = self.host.memory.getProfileName(profile_key)
         if not self.checkClient(profile):
             raise exceptions.ProfileUnknownError("Unknown or disconnected profile")
-        if room_jid.userhost() not in self.clients[profile].joined_rooms:
+        if room_jid not in self.clients[profile].joined_rooms:
             raise UnknownRoom("This room has not been joined")
         return profile
 
@@ -127,12 +127,11 @@
         def _sendBridgeSignal(ignore=None):
             self.host.bridge.roomJoined(room.roomJID.userhost(), [user.nick for user in room.roster.values()], room.nick, profile)
 
-        room_jid_s = room.roomJID.userhost()
-        self.clients[profile].joined_rooms[room_jid_s] = room
+        self.clients[profile].joined_rooms[room.roomJID] = room
         if room.locked:
-            #FIXME: the current behaviour is to create an instant room
-            #and send the signal only when the room is unlocked
-            #a proper configuration management should be done
+            # FIXME: the current behaviour is to create an instant room
+            # and send the signal only when the room is unlocked
+            # a proper configuration management should be done
             print "room locked !"
             self.clients[profile].configure(room.roomJID, {}).addCallbacks(_sendBridgeSignal, lambda x: log.error(_('Error while configuring the room')))
         else:
@@ -164,27 +163,25 @@
             result.append((room.roomJID.userhost(), [user.nick for user in room.roster.values()], room.nick))
         return result
 
-    def getRoomNick(self, room_jid_s, profile_key=C.PROF_KEY_NONE):
+    def getRoomNick(self, room_jid, profile_key=C.PROF_KEY_NONE):
         """return nick used in room by user
 
-        @param room_jid_s: unicode room id
+        @param room_jid (jid.JID): JID of the room
         @profile_key: profile
         @return: nick or empty string in case of error"""
         profile = self.host.memory.getProfileName(profile_key)
-        if not self.checkClient(profile) or room_jid_s not in self.clients[profile].joined_rooms:
+        if not self.checkClient(profile) or room_jid not in self.clients[profile].joined_rooms:
             return ''
-        return self.clients[profile].joined_rooms[room_jid_s].nick
+        return self.clients[profile].joined_rooms[room_jid].nick
 
     def getRoomNickOfUser(self, room, user_jid, secure=True):
         """Returns the nick of the given user in the room.
 
-        @room: instance of wokkel.muc.Room
-        @user: JID or unicode (JID userhost).
-        @param secure: set to True for a secure check
-        @return: the nick or None if the user didn't join the room.
+        @param room (wokkel.muc.Room): the room
+        @param user (jid.JID): bare JID of the user
+        @param secure (bool): set to True for a secure check
+        @return: unicode or None if the user didn't join the room.
         """
-        if not isinstance(user_jid, jid.JID):
-            user_jid = jid.JID(user_jid).userhostJID()
         for user in room.roster.values():
             if user.entity is not None:
                 if user.entity.userhostJID() == user_jid.userhostJID():
@@ -199,11 +196,12 @@
     def getRoomNicksOfUsers(self, room, users=[], secure=True):
         """Returns the nicks of the given users in the room.
 
-        @room: instance of wokkel.muc.Room
-        @users: list of JID or unicode (JID userhost).
-        @param secure: set to True for a secure check
-        @return: (x, y) with x a list containing the nicks of
-        the users who are in the room, and y the missing users.
+        @param room (wokkel.muc.Room): the room
+        @param users (list[jid.JID]): list of users
+        @param secure (True): set to True for a secure check
+        @return: a couple (x, y) with:
+            - x (list[unicode]): nicks of the users who are in the room
+            - y (list[jid.JID]): JID of the missing users.
         """
         nicks = []
         missing = []
@@ -231,6 +229,7 @@
         except KeyError:
             log.error(_("room_jid key is not present !"))
             return defer.fail(exceptions.DataError)
+
         def xmluiReceived(xmlui):
             return {"xmlui": xmlui.toXml()}
         return self.configureRoom(room_jid, profile).addCallback(xmluiReceived)
@@ -277,7 +276,7 @@
     def isNickInRoom(self, room_jid, nick, profile):
         """Tell if a nick is currently present in a room"""
         profile = self.getProfileAssertInRoom(room_jid, profile)
-        return self.clients[profile].joined_rooms[room_jid.userhost()].inRoster(muc.User(nick))
+        return self.clients[profile].joined_rooms[room_jid].inRoster(muc.User(nick))
 
     def getRoomsSubjects(self, profile_key=C.PROF_KEY_NONE):
         """Return received subjects of rooms"""
@@ -296,7 +295,7 @@
         muc_service = None
         services = yield self.host.findServiceEntities("conference", "text", jid_, profile_key=profile_key)
         for service in services:
-            if not ".irc." in service.userhost():
+            if ".irc." not in service.userhost():
                 # FIXME:
                 # This ugly hack is here to avoid an issue with openfire: the IRC gateway
                 # use "conference/text" identity (instead of "conference/irc")
@@ -313,7 +312,7 @@
         @param muc_service (jid.JID) : leave empty string to use the default service
         @return: jid.JID (unique room bare JID)
         """
-        #TODO: we should use #RFC-0045 10.1.4 when available here
+        # TODO: we should use #RFC-0045 10.1.4 when available here
         client = self.host.getClient(profile_key)
         room_name = uuid.uuid1()
         if muc_service is None:
@@ -337,7 +336,7 @@
         profile = self.host.memory.getProfileName(profile_key)
         if not self.checkClient(profile):
             return _errDeferred()
-        if room_jid.userhost() in self.clients[profile].joined_rooms:
+        if room_jid in self.clients[profile].joined_rooms:
             log.warning(_('%(profile)s is already in room %(room_jid)s') % {'profile': profile, 'room_jid': room_jid.userhost()})
             return _errDeferred()
         log.info(_("[%(profile)s] is joining room %(room)s with nick %(nick)s") % {'profile': profile, 'room': room_jid.userhost(), 'nick': nick})
@@ -472,10 +471,10 @@
             return False
 
         if mess_data["unparsed"].strip():
-            room = self.host.plugins[C.TEXT_CMDS].getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host)
-            nick = (self.getRoomNick(mess_data["to"].userhost(), profile) or
+            room_jid = self.host.plugins[C.TEXT_CMDS].getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host)
+            nick = (self.getRoomNick(room_jid, profile) or
                     self.host.getClient(profile).jid.user)
-            self.join(room, nick, {}, profile)
+            self.join(room_jid, nick, {}, profile)
 
         return False
 
@@ -631,10 +630,10 @@
         """ Add MUC user information to whois """
         if mess_data['type'] != "groupchat":
             return
-        if target_jid.userhost() not in self.clients[profile].joined_rooms:
+        if target_jid.userhostJID() not in self.clients[profile].joined_rooms:
             log.warning(_("This room has not been joined"))
             return
-        user = self.clients[profile].joined_rooms[target_jid.userhost()].getUser(target_jid.resource)
+        user = self.clients[profile].joined_rooms[target_jid.userhostJID()].getUser(target_jid.resource)
         whois_msg.append(_("Nickname: %s") % user.nick)
         if user.entity:
             whois_msg.append(_("Entity: %s") % user.entity)
@@ -650,32 +649,35 @@
     def presenceTrigger(self, presence_elt, client):
         # XXX: shouldn't it be done by the server ?!!
         muc_client = self.clients[client.profile]
-        for room_jid_s, room in muc_client.joined_rooms.items():
+        for room_jid, room in muc_client.joined_rooms.iteritems():
             elt = copy.deepcopy(presence_elt)
-            elt['to'] = room_jid_s + '/' + room.nick
+            elt['to'] = room_jid.userhost() + '/' + room.nick
             client.presence.send(elt)
         return True
 
 
 class SatMUCClient (muc.MUCClient):
-    #implements(iwokkel.IDisco)
+    # implements(iwokkel.IDisco)
 
     def __init__(self, plugin_parent):
         self.plugin_parent = plugin_parent
         self.host = plugin_parent.host
         muc.MUCClient.__init__(self)
-        self.joined_rooms = {}  # FIXME: seem to do the same thing as MUCClient's _rooms attribute, must be removed
         self.rec_subjects = {}
         self.__changing_nicks = set()  # used to keep trace of who is changing nick,
                                        # and to discard userJoinedRoom signal in this case
         print "init SatMUCClient OK"
 
+    @property
+    def joined_rooms(self):
+        return self._rooms
+
     def subject(self, room, subject):
         return muc.MUCClientProtocol.subject(self, room, subject)
 
     def unavailableReceived(self, presence):
-        #XXX: we override this method to manage nickname change
-        #TODO: feed this back to Wokkel
+        # XXX: we override this method to manage nickname change
+        # TODO: feed this back to Wokkel
         """
         Unavailable presence was received.
 
@@ -714,9 +716,8 @@
             # we left the room
             room_jid_s = room.roomJID.userhost()
             log.info(_("Room [%(room)s] left (%(profile)s))") % {"room": room_jid_s,
-                                                             "profile": self.parent.profile})
+                                                                 "profile": self.parent.profile})
             self.host.memory.delEntityCache(room.roomJID, profile_key=self.parent.profile)
-            del self.plugin_parent.clients[self.parent.profile].joined_rooms[room_jid_s]
             self.host.bridge.roomLeft(room.roomJID.userhost(), self.parent.profile)
         else:
             log.debug(_("user %(nick)s left room (%(room_id)s)") % {'nick': user.nick, 'room_id': room.occupantJID.userhost()})
@@ -734,7 +735,7 @@
 
     def receivedHistory(self, room, user, message):
         # http://xmpp.org/extensions/xep-0045.html#enter-history
-        #log.debug('receivedHistory: room=%s user=%s body=%s' % (room.roomJID.full(), user, message))
+        # log.debug('receivedHistory: room=%s user=%s body=%s' % (room.roomJID.full(), user, message))
         pass
 
     def receivedSubject(self, room, user, subject):
--- a/src/plugins/plugin_xep_0249.py	Mon Mar 09 16:37:15 2015 +0100
+++ b/src/plugins/plugin_xep_0249.py	Wed Mar 11 12:35:21 2015 +0100
@@ -120,18 +120,18 @@
         #TODO: check parameters validity
         self.invite(jid.JID(target), jid.JID("%s@%s" % (roomId, service)), options, profile_key)
 
-    def _accept(self, room, profile_key=C.PROF_KEY_NONE):
-        """
-        Accept the invitation to join a MUC
-        @param room: room jid as string
+    def _accept(self, room_jid, profile_key=C.PROF_KEY_NONE):
+        """Accept the invitation to join a MUC.
+
+        @param room (jid.JID): JID of the room
         """
         profile = self.host.memory.getProfileName(profile_key)
         if not profile:
             log.error(_("Profile doesn't exists !"))
             return
-        log.info(_('Invitation accepted for room %(room)s [%(profile)s]') % {'room': room, 'profile': profile})
+        log.info(_('Invitation accepted for room %(room)s [%(profile)s]') % {'room': room_jid.userhost(), 'profile': profile})
         _jid, xmlstream = self.host.getJidNStream(profile)
-        d = self.host.plugins["XEP-0045"].join(jid.JID(room), _jid.user, {}, profile)
+        d = self.host.plugins["XEP-0045"].join(room_jid, _jid.user, {}, profile)
         return d
 
     def onInvitation(self, message, profile):
@@ -141,28 +141,29 @@
         @profile: %(doc_profile)s
         """
         try:
-            room = message.firstChildElement()['jid']
-            log.info(_('Invitation received for room %(room)s [%(profile)s]') % {'room': room, 'profile': profile})
+            room_jid_s = message.firstChildElement()['jid']
+            log.info(_('Invitation received for room %(room)s [%(profile)s]') % {'room': room_jid_s, 'profile': profile})
         except:
             log.error(_('Error while parsing invitation'))
             return
-        from_ = message["from"]
-        if room in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
+        from_jid_s = message["from"]
+        room_jid = jid.JID(room_jid_s)
+        if room_jid in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
             log.info(_("Invitation silently discarded because user is already in the room."))
             return
         autojoin = self.host.memory.getParamA(AUTOJOIN_NAME, AUTOJOIN_KEY, profile_key=profile)
 
         def accept_cb(conf_id, accepted, data, profile):
-            if conf_id == room and accepted:
-                self._accept(room, profile)
+            if conf_id == room_jid_s and accepted:
+                self._accept(room_jid, profile)
 
         if autojoin == "always":
-            self._accept(room, profile)
+            self._accept(room_jid, profile)
         elif autojoin == "never":
-            self.host.bridge.newAlert(_("An invitation from %(user)s to join the room %(room)s has been declined according to your personal settings.") % {'user': from_, 'room': room}, _("MUC invitation"), "INFO", profile)
+            self.host.bridge.newAlert(_("An invitation from %(user)s to join the room %(room)s has been declined according to your personal settings.") % {'user': from_jid_s, 'room': room_jid_s}, _("MUC invitation"), "INFO", profile)
         else:  # leave the default value here
-            data = {"message": _("You have been invited by %(user)s to join the room %(room)s. Do you accept?") % {'user': from_, 'room': room}, "title": _("MUC invitation")}
-            self.host.askConfirmation(room, "YES/NO", data, accept_cb, profile)
+            data = {"message": _("You have been invited by %(user)s to join the room %(room)s. Do you accept?") % {'user': from_jid_s, 'room': room_jid_s}, "title": _("MUC invitation")}
+            self.host.askConfirmation(room_jid_s, "YES/NO", data, accept_cb, profile)
 
     def cmd_invite(self, mess_data, profile):
         """invite someone in the room