diff src/plugins/plugin_misc_imap.py @ 594:e629371a28d3

Fix pep8 support in src/plugins.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:35 +0100
parents beaf6bec2fcd
children 84a6e83157c2
line wrap: on
line diff
--- a/src/plugins/plugin_misc_imap.py	Mon Jan 21 00:59:50 2013 +0100
+++ b/src/plugins/plugin_misc_imap.py	Fri Jan 18 17:55:35 2013 +0100
@@ -21,34 +21,33 @@
 
 from logging import debug, info, error
 import warnings
-from twisted.internet import protocol,defer
+from twisted.internet import protocol, defer
 from twisted.words.protocols.jabber import error as jab_error
-from twisted.cred import portal,checkers,credentials
+from twisted.cred import portal, checkers, credentials
 from twisted.cred import error as cred_error
 from twisted.mail import imap4
 from twisted.python import failure
 from email.parser import Parser
 import email.message
-import os,os.path
+import os
 from cStringIO import StringIO
 from twisted.internet import reactor
 import pdb
 
-
 from zope.interface import implements
 
-
 PLUGIN_INFO = {
-"name": "IMAP server Plugin",
-"import_name": "IMAP",
-"type": "Misc",
-"protocols": [],
-"dependencies": ["Maildir"],
-"main": "IMAP_server",
-"handler": "no",
-"description": _("""Create an Imap server that you can use to read your "normal" type messages""")
+    "name": "IMAP server Plugin",
+    "import_name": "IMAP",
+    "type": "Misc",
+    "protocols": [],
+    "dependencies": ["Maildir"],
+    "main": "IMAP_server",
+    "handler": "no",
+    "description": _("""Create an Imap server that you can use to read your "normal" type messages""")
 }
 
+
 class IMAP_server(object):
     #TODO: connect profile on mailbox request, once password is accepted
 
@@ -75,15 +74,16 @@
         self.server_factory = ImapServerFactory(self.host)
         reactor.listenTCP(port, self.server_factory)
 
+
 class Message(object):
     implements(imap4.IMessage)
 
     def __init__(self, uid, flags, mess_fp):
         debug('Message Init')
-        self.uid=uid
-        self.flags=flags
-        self.mess_fp=mess_fp
-        self.message=Parser().parse(mess_fp)
+        self.uid = uid
+        self.flags = flags
+        self.mess_fp = mess_fp
+        self.message = Parser().parse(mess_fp)
 
     def getUID(self):
         """Retrieve the unique identifier associated with this message.
@@ -105,7 +105,6 @@
         debug('getInternalDate')
         return self.message['Date']
 
-
     def getHeaders(self, negate, *names):
         """Retrieve a group of message headers.
         @param names: The names of the headers to retrieve or omit.
@@ -114,12 +113,12 @@
         @return: A mapping of header field names to header field values
         """
         debug('getHeaders %s - %s' % (negate, names))
-        final_dict={}
-        to_check=[name.lower() for name in names]
+        final_dict = {}
+        to_check = [name.lower() for name in names]
         for header in self.message.keys():
             if (negate and not header.lower() in to_check) or \
-              (not negate and header.lower() in to_check):
-                final_dict[header]=self.message[header]
+                    (not negate and header.lower() in to_check):
+                final_dict[header] = self.message[header]
         return final_dict
 
     def getBodyFile(self):
@@ -132,17 +131,16 @@
         """Retrieve the total size, in octets, of this message.
         """
         debug('getSize')
-        self.mess_fp.seek(0,os.SEEK_END)
+        self.mess_fp.seek(0, os.SEEK_END)
         return self.mess_fp.tell()
 
-
     def isMultipart(self):
         """Indicate whether this message has subparts.
         """
         debug('isMultipart')
         return False
 
-    def getSubPart(self,part):
+    def getSubPart(self, part):
         """Retrieve a MIME sub-message
         @param part: The number of the part to retrieve, indexed from 0.
         @return: The specified sub-part.
@@ -154,39 +152,39 @@
 class SatMailbox(object):
     implements(imap4.IMailbox)
 
-    def __init__(self,host,name,profile):
+    def __init__(self, host, name, profile):
         self.host = host
-        self.listeners=set()
-        debug ('Mailbox init (%s)', name)
-        if name!="INBOX":
+        self.listeners = set()
+        debug('Mailbox init (%s)', name)
+        if name != "INBOX":
             raise imap4.MailboxException("Only INBOX is managed for the moment")
-        self.mailbox=self.host.plugins["Maildir"].accessMessageBox(name,self.newMessage, profile)
+        self.mailbox = self.host.plugins["Maildir"].accessMessageBox(name, self.newMessage, profile)
 
     def newMessage(self):
         """Called when a new message is in the mailbox"""
-        debug ("newMessage signal received")
-        nb_messages=self.getMessageCount()
+        debug("newMessage signal received")
+        nb_messages = self.getMessageCount()
         for listener in self.listeners:
-            listener.newMessages(nb_messages,None)
+            listener.newMessages(nb_messages, None)
 
     def getUIDValidity(self):
         """Return the unique validity identifier for this mailbox.
         """
-        debug ('getUIDValidity')
+        debug('getUIDValidity')
         return 0
 
     def getUIDNext(self):
         """Return the likely UID for the next message added to this mailbox.
         """
-        debug ('getUIDNext')
+        debug('getUIDNext')
         return self.mailbox.getNextUid()
 
-    def getUID(self,message):
+    def getUID(self, message):
         """Return the UID of a message in the mailbox
         @param message: The message sequence number
         @return: The UID of the message.
         """
-        debug ('getUID (%i)' % message)
+        debug('getUID (%i)' % message)
         #return self.mailbox.getUid(message-1) #XXX: it seems that this method get uid and not message sequence number
         return message
 
@@ -208,7 +206,7 @@
         """Return the number of messages with the 'Unseen' flag.
         """
         debug('getUnseenCount')
-        return self.getMessageCount()-len(self.mailbox.getMessageIdsWithFlag('\\SEEN'))
+        return self.getMessageCount() - len(self.mailbox.getMessageIdsWithFlag('\\SEEN'))
 
     def isWriteable(self):
         """Get the read/write status of the mailbox.
@@ -222,7 +220,6 @@
         """
         debug('destroy')
 
-
     def requestStatus(self, names):
         """Return status information about this mailbox.
         @param names: The status names to return information regarding.
@@ -262,7 +259,7 @@
         else:
             raise imap4.MailboxException('Trying to remove an unknown listener')
 
-    def addMessage(self, message, flags = (), date = None):
+    def addMessage(self, message, flags=(), date=None):
         """Add the given message to this mailbox.
         @param message: The RFC822 formatted message
         @param flags: The flags to associate with this message
@@ -288,24 +285,24 @@
         about
         @param uid: If true, the IDs specified in the query are UIDs;
         """
-        debug('fetch (%s, %s)'%(messages,uid))
+        debug('fetch (%s, %s)' % (messages, uid))
         if uid:
             messages.last = self.mailbox.getMaxUid()
             messages.getnext = self.mailbox.getNextExistingUid
             for mess_uid in messages:
-                if mess_uid == None:
-                    debug ('stopping iteration')
+                if mess_uid is None:
+                    debug('stopping iteration')
                     raise StopIteration
                 try:
-                    yield (mess_uid,Message(mess_uid,self.mailbox.getFlagsUid(mess_uid), self.mailbox.getMessageUid(mess_uid)))
+                    yield (mess_uid, Message(mess_uid, self.mailbox.getFlagsUid(mess_uid), self.mailbox.getMessageUid(mess_uid)))
                 except IndexError:
                     continue
         else:
             messages.last = self.getMessageCount()
             for mess_idx in messages:
-                if mess_idx>self.getMessageCount():
+                if mess_idx > self.getMessageCount():
                     raise StopIteration
-                yield (mess_idx,Message(mess_idx,self.mailbox.getFlags(mess_idx),self.mailbox.getMessage(mess_idx-1)))
+                yield (mess_idx, Message(mess_idx, self.mailbox.getFlags(mess_idx), self.mailbox.getMessage(mess_idx - 1)))
 
     def store(self, messages, flags, mode, uid):
         """Set the flags of one or more messages.
@@ -324,19 +321,19 @@
         """
         debug('store')
 
-        flags=[flag.upper() for flag in flags]
+        flags = [flag.upper() for flag in flags]
 
-        def updateFlags(getF,setF):
+        def updateFlags(getF, setF):
             ret = {}
             for mess_id in messages:
-                if (uid and mess_id == None) or (not uid and mess_id>self.getMessageCount()):
+                if (uid and mess_id is None) or (not uid and mess_id > self.getMessageCount()):
                     break
-                _flags=set(getF(mess_id) if mode else [])
-                if mode==-1:
+                _flags = set(getF(mess_id) if mode else [])
+                if mode == -1:
                     _flags.difference_update(set(flags))
                 else:
                     _flags.update(set(flags))
-                new_flags=list(_flags)
+                new_flags = list(_flags)
                 setF(mess_id, new_flags)
                 ret[mess_id] = tuple(new_flags)
             return ret
@@ -344,15 +341,15 @@
         if uid:
             messages.last = self.mailbox.getMaxUid()
             messages.getnext = self.mailbox.getNextExistingUid
-            ret = updateFlags(self.mailbox.getFlagsUid,self.mailbox.setFlagsUid)
+            ret = updateFlags(self.mailbox.getFlagsUid, self.mailbox.setFlagsUid)
             for listener in self.listeners:
                 listener.flagsChanged(ret)
             return ret
 
         else:
             messages.last = self.getMessageCount()
-            ret = updateFlags(self.mailbox.getFlags,self.mailbox.setFlags)
-            newFlags={}
+            ret = updateFlags(self.mailbox.getFlags, self.mailbox.setFlags)
+            newFlags = {}
             for idx in ret:
                 #we have to convert idx to uid for the listeners
                 newFlags[self.mailbox.getUid(idx)] = ret[idx]
@@ -366,7 +363,7 @@
         @return: A list of the flags that can be set on messages in this mailbox.
         """
         debug('getFlags')
-        return ['\\SEEN','\\ANSWERED','\\FLAGGED','\\DELETED','\\DRAFT'] #TODO: add '\\RECENT'
+        return ['\\SEEN', '\\ANSWERED', '\\FLAGGED', '\\DELETED', '\\DRAFT']  # TODO: add '\\RECENT'
 
     def getHierarchicalDelimiter(self):
         """Get the character which delimits namespaces for in this mailbox.
@@ -374,33 +371,35 @@
         debug('getHierarchicalDelimiter')
         return '.'
 
+
 class ImapSatAccount(imap4.MemoryAccount):
     #implements(imap4.IAccount)
 
     def __init__(self, host, profile):
         debug("ImapAccount init")
-        self.host=host
-        self.profile=profile
-        imap4.MemoryAccount.__init__(self,profile)
-        self.addMailbox("Inbox") #We only manage Inbox for the moment
-        debug ('INBOX added')
+        self.host = host
+        self.profile = profile
+        imap4.MemoryAccount.__init__(self, profile)
+        self.addMailbox("Inbox")  # We only manage Inbox for the moment
+        debug('INBOX added')
 
     def _emptyMailbox(self, name, id):
-        return SatMailbox(self.host,name,self.profile)
+        return SatMailbox(self.host, name, self.profile)
 
 
 class ImapRealm(object):
     implements(portal.IRealm)
 
-    def __init__(self,host):
+    def __init__(self, host):
         self.host = host
 
     def requestAvatar(self, avatarID, mind, *interfaces):
         debug('requestAvatar')
-        profile=avatarID.decode('utf-8')
+        profile = avatarID.decode('utf-8')
         if imap4.IAccount not in interfaces:
             raise NotImplementedError
-        return imap4.IAccount, ImapSatAccount(self.host,profile), lambda:None
+        return imap4.IAccount, ImapSatAccount(self.host, profile), lambda: None
+
 
 class SatProfileCredentialChecker(object):
     """
@@ -412,7 +411,6 @@
     credentialInterfaces = (credentials.IUsernamePassword,
                             credentials.IUsernameHashedPassword)
 
-
     def __init__(self, host):
         self.host = host
 
@@ -431,20 +429,21 @@
         d.addCallback(self._cbPasswordMatch, credentials.username)
         return d
 
+
 class ImapServerFactory(protocol.ServerFactory):
     protocol = imap4.IMAP4Server
 
     def __init__(self, host):
-        self.host=host
+        self.host = host
 
     def startedConnecting(self, connector):
-        debug (_("IMAP server connection started"))
+        debug(_("IMAP server connection started"))
 
     def clientConnectionLost(self, connector, reason):
-        debug (_("IMAP server connection lost (reason: %s)"), reason)
+        debug(_("IMAP server connection lost (reason: %s)"), reason)
 
     def buildProtocol(self, addr):
-        debug ("Building protocol")
+        debug("Building protocol")
         prot = protocol.ServerFactory.buildProtocol(self, addr)
         prot.portal = portal.Portal(ImapRealm(self.host))
         prot.portal.registerChecker(SatProfileCredentialChecker(self.host))