diff src/core/xmpp.py @ 589:d1b4805124a1

Fix pep8 support in src/core.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:35 +0100
parents 952322b1d490
children 84a6e83157c2
line wrap: on
line diff
--- a/src/core/xmpp.py	Fri Jan 18 17:55:35 2013 +0100
+++ b/src/core/xmpp.py	Fri Jan 18 17:55:35 2013 +0100
@@ -22,7 +22,7 @@
 from twisted.internet import task, defer
 from twisted.words.protocols.jabber import jid, xmlstream
 from wokkel import client, disco, xmppim, generic, compat, delay
-from logging import debug, info, error
+from logging import debug, info, warning, error
 from sat.core import exceptions
 from calendar import timegm
 
@@ -32,14 +32,13 @@
     def __init__(self, host_app, profile, user_jid, password, host=None, port=5222):
         client.XMPPClient.__init__(self, user_jid, password, host, port)
         self.factory.clientConnectionLost = self.connectionLost
-        self.__connected=False
+        self.__connected = False
         self.profile = profile
         self.host_app = host_app
         self.client_initialized = defer.Deferred()
         self.conn_deferred = defer.Deferred()
-        self._waiting_conf = {}  #callback called when a confirmation is received
-        self._progress_cb_map = {}  #callback called when a progress is requested (key = progress id)
-
+        self._waiting_conf = {}  # callback called when a confirmation is received
+        self._progress_cb_map = {}  # callback called when a progress is requested (key = progress id)
 
     def getConnectionDeferred(self):
         """Return a deferred which fire when the client is connected"""
@@ -49,16 +48,15 @@
         if not self.host_app.trigger.point("XML Initialized", xmlstream, self.profile):
             return
         client.XMPPClient._authd(self, xmlstream)
-        self.__connected=True
-        info (_("********** [%s] CONNECTED **********") % self.profile)
+        self.__connected = True
+        info(_("********** [%s] CONNECTED **********") % self.profile)
         self.streamInitialized()
-        self.host_app.bridge.connected(self.profile) #we send the signal to the clients
-
+        self.host_app.bridge.connected(self.profile)  # we send the signal to the clients
 
     def streamInitialized(self):
         """Called after _authd"""
-        debug (_("XML stream is initialized"))
-        self.keep_alife = task.LoopingCall(self.xmlstream.send, " ")  #Needed to avoid disconnection (specially with openfire)
+        debug(_("XML stream is initialized"))
+        self.keep_alife = task.LoopingCall(self.xmlstream.send, " ")  # Needed to avoid disconnection (specially with openfire)
         self.keep_alife.start(180)
 
         self.disco = SatDiscoProtocol(self)
@@ -73,18 +71,18 @@
 
         self.presence.available()
 
-        self.disco.requestInfo(jid.JID(self.jid.host)).addCallback(self.host_app.serverDisco, self.profile)  #FIXME: use these informations
+        self.disco.requestInfo(jid.JID(self.jid.host)).addCallback(self.host_app.serverDisco, self.profile)  # FIXME: use these informations
 
         self.disco.requestItems(jid.JID(self.jid.host)).addCallback(self.host_app.serverDiscoItems, self.disco, self.profile, self.client_initialized)
         self.conn_deferred.callback(None)
 
     def initializationFailed(self, reason):
-        print ("initializationFailed: %s" % reason)
+        print "initializationFailed: %s" % reason
         self.host_app.bridge.connectionError("AUTH_ERROR", self.profile)
         try:
             client.XMPPClient.initializationFailed(self, reason)
         except:
-            #we already send an error signal, no need to raise an exception
+            # we already send an error signal, no need to raise an exception
             pass
         self.conn_deferred.errback()
 
@@ -92,14 +90,14 @@
         return self.__connected
 
     def connectionLost(self, connector, unused_reason):
-        self.__connected=False
-        info (_("********** [%s] DISCONNECTED **********") % self.profile)
+        self.__connected = False
+        info(_("********** [%s] DISCONNECTED **********") % self.profile)
         try:
             self.keep_alife.stop()
         except AttributeError:
-            debug (_("No keep_alife"))
-        self.host_app.bridge.disconnected(self.profile) #we send the signal to the clients
-        self.host_app.purgeClient(self.profile) #and we remove references to this client
+            debug(_("No keep_alife"))
+        self.host_app.bridge.disconnected(self.profile)  # we send the signal to the clients
+        self.host_app.purgeClient(self.profile)  # and we remove references to this client
 
 
 class SatMessageProtocol(xmppim.MessageProtocol):
@@ -109,7 +107,7 @@
         self.host = host
 
     def onMessage(self, message):
-        debug (_(u"got message from: %s"), message["from"])
+        debug(_(u"got message from: %s"), message["from"])
         if not self.host.trigger.point("MessageReceived", message, profile=self.parent.profile):
             return
         for e in message.elements():
@@ -120,7 +118,7 @@
                     _delay = delay.Delay.fromElement(filter(lambda elm: elm.name == 'delay', message.elements())[0])
                     timestamp = timegm(_delay.stamp.utctimetuple())
                     extra = {"archive": str(timestamp)}
-                    if mess_type != 'groupchat': #XXX: we don't save delayed messages in history for groupchats
+                    if mess_type != 'groupchat':  # XXX: we don't save delayed messages in history for groupchats
                         #TODO: add delayed messages to history if they aren't already in it
                         self.host.memory.addToHistory(jid.JID(message["from"]), jid.JID(message["to"]), mess_body, mess_type, timestamp, profile=self.parent.profile)
                 except IndexError:
@@ -129,6 +127,7 @@
                 self.host.bridge.newMessage(message["from"], mess_body, mess_type, message['to'], extra, profile=self.parent.profile)
                 break
 
+
 class SatRosterProtocol(xmppim.RosterClientProtocol):
 
     def __init__(self, host):
@@ -136,8 +135,8 @@
         self.host = host
         self.got_roster = defer.Deferred()
         #XXX: the two following dicts keep a local copy of the roster
-        self._groups = {} #map from groups to bare jids: key=group value=set of bare jids
-        self._jids = {} #map from bare jids to RosterItem: key=jid value=RosterItem
+        self._groups = {}  # map from groups to bare jids: key=group value=set of bare jids
+        self._jids = {}  # map from bare jids to RosterItem: key=jid value=RosterItem
 
     def rosterCb(self, roster):
         for raw_jid, item in roster.iteritems():
@@ -193,17 +192,17 @@
         #TODO: send a signal to frontends
         if not item.subscriptionTo and not item.subscriptionFrom and not item.ask:
             #XXX: current behaviour: we don't want contact in our roster list
-            #if there is no presence subscription
-            #may change in the future
+            # if there is no presence subscription
+            # may change in the future
             self.removeItem(item.jid)
             return
-        info (_("new contact in roster list: %s"), item.jid.full())
+        info(_("new contact in roster list: %s"), item.jid.full())
         #self.host.memory.addContact(item.jid, item_attr, item.groups, self.parent.profile)
 
         bare_jid = item.jid.userhost()
         self._jids[bare_jid] = item
         for group in item.groups:
-            self._groups.setdefault(group,set()).add(bare_jid)
+            self._groups.setdefault(group, set()).add(bare_jid)
         self.host.bridge.newContact(item.jid.full(), self.getAttributes(item), item.groups, self.parent.profile)
 
     def onRosterRemove(self, entity):
@@ -211,11 +210,11 @@
         print _("removing %s from roster list") % entity.full()
         bare_jid = entity.userhost()
 
-        #we first remove item from local cache (self._groups and self._jids)
+        # we first remove item from local cache (self._groups and self._jids)
         try:
             item = self._jids.pop(bare_jid)
         except KeyError:
-            log.warning("Received a roster remove event for an item not in cache")
+            warning("Received a roster remove event for an item not in cache")
             return
         for group in item.groups:
             try:
@@ -224,10 +223,10 @@
                 if not jids_set:
                     del self._groups[group]
             except KeyError:
-                log.warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" %
-                            {"group": group, "jid": bare_jid})
+                warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" %
+                        {"group": group, "jid": bare_jid})
 
-        #then we send the bridge signal
+        # then we send the bridge signal
         self.host.bridge.contactDeleted(entity.userhost(), self.parent.profile)
 
     def getGroups(self):
@@ -256,7 +255,7 @@
         try:
             return self._groups[group]
         except KeyError:
-            return  exceptions.UnknownGroupError
+            return exceptions.UnknownGroupError
 
 
 class SatPresenceProtocol(xmppim.PresenceClientProtocol):
@@ -266,37 +265,38 @@
         self.host = host
 
     def availableReceived(self, entity, show=None, statuses=None, priority=0):
-        debug (_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity':entity, 'show':show, 'statuses':statuses, 'priority':priority})
+        debug(_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity': entity, 'show': show, 'statuses': statuses, 'priority': priority})
 
         if not statuses:
             statuses = {}
 
-        if statuses.has_key(None):   #we only want string keys
+        if None in statuses:  # we only want string keys
             statuses["default"] = statuses[None]
             del statuses[None]
 
         self.host.memory.setPresenceStatus(entity, show or "",
-                int(priority), statuses, self.parent.profile)
+                                           int(priority), statuses,
+                                           self.parent.profile)
 
-        #now it's time to notify frontends
-        self.host.bridge.presenceUpdate(entity.full(),  show or "",
-                int(priority), statuses, self.parent.profile)
+        # now it's time to notify frontends
+        self.host.bridge.presenceUpdate(entity.full(), show or "",
+                                        int(priority), statuses,
+                                        self.parent.profile)
 
     def unavailableReceived(self, entity, statuses=None):
-        debug (_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity':entity, 'statuses':statuses})
+        debug(_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity': entity, 'statuses': statuses})
 
         if not statuses:
             statuses = {}
 
-        if statuses.has_key(None):   #we only want string keys
+        if None in statuses:  # we only want string keys
             statuses["default"] = statuses[None]
             del statuses[None]
         self.host.memory.setPresenceStatus(entity, "unavailable", 0, statuses, self.parent.profile)
 
-        #now it's time to notify frontends
+        # now it's time to notify frontends
         self.host.bridge.presenceUpdate(entity.full(), "unavailable", 0, statuses, self.parent.profile)
 
-
     def available(self, entity=None, show=None, statuses=None, priority=0):
         if not statuses:
             statuses = {}
@@ -319,7 +319,7 @@
         xmppim.PresenceClientProtocol.subscribed(self, entity)
         self.host.memory.delWaitingSub(entity.userhost(), self.parent.profile)
         item = self.parent.roster.getItem(entity)
-        if not item or not item.subscriptionTo: #we automatically subscribe to 'to' presence
+        if not item or not item.subscriptionTo:  # we automatically subscribe to 'to' presence
             debug(_('sending automatic "from" subscription request'))
             self.subscribe(entity)
 
@@ -328,18 +328,18 @@
         self.host.memory.delWaitingSub(entity.userhost(), self.parent.profile)
 
     def subscribedReceived(self, entity):
-        debug (_("subscription approved for [%s]") % entity.userhost())
+        debug(_("subscription approved for [%s]") % entity.userhost())
         self.host.bridge.subscribe('subscribed', entity.userhost(), self.parent.profile)
 
     def unsubscribedReceived(self, entity):
-        debug (_("unsubscription confirmed for [%s]") % entity.userhost())
+        debug(_("unsubscription confirmed for [%s]") % entity.userhost())
         self.host.bridge.subscribe('unsubscribed', entity.userhost(), self.parent.profile)
 
     def subscribeReceived(self, entity):
-        debug (_("subscription request from [%s]") % entity.userhost())
+        debug(_("subscription request from [%s]") % entity.userhost())
         item = self.parent.roster.getItem(entity)
         if item and item.subscriptionTo:
-            #We automatically accept subscription if we are already subscribed to contact presence
+            # We automatically accept subscription if we are already subscribed to contact presence
             debug(_('sending automatic subscription acceptance'))
             self.subscribed(entity)
         else:
@@ -347,27 +347,30 @@
             self.host.bridge.subscribe('subscribe', entity.userhost(), self.parent.profile)
 
     def unsubscribeReceived(self, entity):
-        debug (_("unsubscription asked for [%s]") % entity.userhost())
+        debug(_("unsubscription asked for [%s]") % entity.userhost())
         item = self.parent.roster.getItem(entity)
-        if item and item.subscriptionFrom: #we automatically remove contact
+        if item and item.subscriptionFrom:  # we automatically remove contact
             debug(_('automatic contact deletion'))
             self.host.delContact(entity.userhost(), self.parent.profile)
         self.host.bridge.subscribe('unsubscribe', entity.userhost(), self.parent.profile)
 
+
 class SatDiscoProtocol(disco.DiscoClientProtocol):
     def __init__(self, host):
         disco.DiscoClientProtocol.__init__(self)
 
+
 class SatFallbackHandler(generic.FallbackHandler):
     def __init__(self, host):
         generic.FallbackHandler.__init__(self)
 
     def iqFallback(self, iq):
-        if iq.handled == True:
+        if iq.handled is True:
             return
-        debug (u"iqFallback: xml = [%s]" % (iq.toXml()))
+        debug(u"iqFallback: xml = [%s]" % (iq.toXml()))
         generic.FallbackHandler.iqFallback(self, iq)
 
+
 class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
 
     def __init__(self, host, jabber_host, user_login, user_pass, email, answer_id, profile):
@@ -379,7 +382,7 @@
         self.user_email = email
         self.answer_id = answer_id
         self.profile = profile
-        print _("Registration asked for"),user_login, user_pass, jabber_host
+        print _("Registration asked for"), user_login, user_pass, jabber_host
 
     def connectionMade(self):
         print "connectionMade"
@@ -400,25 +403,26 @@
         reg = iq.send(self.jabber_host).addCallbacks(self.registrationAnswer, self.registrationFailure)
 
     def registrationAnswer(self, answer):
-        debug (_("registration answer: %s") % answer.toXml())
+        debug(_("registration answer: %s") % answer.toXml())
         answer_type = "SUCCESS"
-        answer_data={"message":_("Registration successfull")}
+        answer_data = {"message": _("Registration successfull")}
         self.host.bridge.actionResult(answer_type, self.answer_id, answer_data, self.profile)
         self.xmlstream.sendFooter()
 
     def registrationFailure(self, failure):
-        info (_("Registration failure: %s") % str(failure.value))
+        info(_("Registration failure: %s") % str(failure.value))
         answer_type = "ERROR"
         answer_data = {}
         if failure.value.condition == 'conflict':
             answer_data['reason'] = 'conflict'
-            answer_data={"message":_("Username already exists, please choose an other one")}
+            answer_data = {"message": _("Username already exists, please choose an other one")}
         else:
             answer_data['reason'] = 'unknown'
-            answer_data={"message":_("Registration failed (%s)") % str(failure.value.condition)}
+            answer_data = {"message": _("Registration failed (%s)") % str(failure.value.condition)}
         self.host.bridge.actionResult(answer_type, self.answer_id, answer_data, self.profile)
         self.xmlstream.sendFooter()
 
+
 class SatVersionHandler(generic.VersionHandler):
 
     def getDiscoInfo(self, requestor, target, node):
@@ -428,4 +432,3 @@
         # disco features, and when the server (seen on ejabberd) generate its own hash for security check
         # it reject our features (resulting in e.g. no notification on PEP)
         return generic.VersionHandler.getDiscoInfo(self, requestor, target, None)
-