code style reformatting using black

This commit is contained in:
Goffi 2018-06-27 20:14:46 +02:00
commit 744cb0c503

View file

@ -20,6 +20,7 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet import protocol, defer
from twisted.cred import portal, checkers, credentials
@ -41,12 +42,14 @@ PLUGIN_INFO = {
C.PI_DEPENDENCIES: ["Maildir"],
C.PI_MAIN: "IMAP_server",
C.PI_HANDLER: "no",
C.PI_DESCRIPTION: _("""Create an Imap server that you can use to read your "normal" type messages""")
C.PI_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
# TODO: connect profile on mailbox request, once password is accepted
params = """
<params>
@ -62,7 +65,7 @@ class IMAP_server(object):
log.info(_("Plugin Imap Server initialization"))
self.host = host
#parameters
# parameters
host.memory.updateParams(self.params)
port = int(self.host.memory.getParamA("IMAP Port", "Mail Server"))
@ -76,7 +79,7 @@ class Message(object):
implements(imap4.IMessage)
def __init__(self, uid, flags, mess_fp):
log.debug('Message Init')
log.debug("Message Init")
self.uid = uid
self.flags = flags
self.mess_fp = mess_fp
@ -85,22 +88,22 @@ class Message(object):
def getUID(self):
"""Retrieve the unique identifier associated with this message.
"""
log.debug('getUID (message)')
log.debug("getUID (message)")
return self.uid
def getFlags(self):
"""Retrieve the flags associated with this message.
@return: The flags, represented as strings.
"""
log.debug('getFlags')
log.debug("getFlags")
return self.flags
def getInternalDate(self):
"""Retrieve the date internally associated with this message.
@return: An RFC822-formatted date string.
"""
log.debug('getInternalDate')
return self.message['Date']
log.debug("getInternalDate")
return self.message["Date"]
def getHeaders(self, negate, *names):
"""Retrieve a group of message headers.
@ -109,32 +112,33 @@ class Message(object):
should be omitted from the return value, rather than included.
@return: A mapping of header field names to header field values
"""
log.debug(u'getHeaders %s - %s' % (negate, names))
log.debug(u"getHeaders %s - %s" % (negate, 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):
if (negate and not header.lower() in to_check) or (
not negate and header.lower() in to_check
):
final_dict[header] = self.message[header]
return final_dict
def getBodyFile(self):
"""Retrieve a file object containing only the body of this message.
"""
log.debug('getBodyFile')
log.debug("getBodyFile")
return StringIO(self.message.get_payload())
def getSize(self):
"""Retrieve the total size, in octets, of this message.
"""
log.debug('getSize')
log.debug("getSize")
self.mess_fp.seek(0, os.SEEK_END)
return self.mess_fp.tell()
def isMultipart(self):
"""Indicate whether this message has subparts.
"""
log.debug('isMultipart')
log.debug("isMultipart")
return False
def getSubPart(self, part):
@ -142,7 +146,7 @@ class Message(object):
@param part: The number of the part to retrieve, indexed from 0.
@return: The specified sub-part.
"""
log.debug('getSubPart')
log.debug("getSubPart")
return TypeError
@ -152,10 +156,12 @@ class SatMailbox(object):
def __init__(self, host, name, profile):
self.host = host
self.listeners = set()
log.debug(u'Mailbox init (%s)' % name)
log.debug(u"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.messageNew, profile)
self.mailbox = self.host.plugins["Maildir"].accessMessageBox(
name, self.messageNew, profile
)
def messageNew(self):
"""Called when a new message is in the mailbox"""
@ -167,13 +173,13 @@ class SatMailbox(object):
def getUIDValidity(self):
"""Return the unique validity identifier for this mailbox.
"""
log.debug('getUIDValidity')
log.debug("getUIDValidity")
return 0
def getUIDNext(self):
"""Return the likely UID for the next message added to this mailbox.
"""
log.debug('getUIDNext')
log.debug("getUIDNext")
return self.mailbox.getNextUid()
def getUID(self, message):
@ -181,14 +187,14 @@ class SatMailbox(object):
@param message: The message sequence number
@return: The UID of the message.
"""
log.debug(u'getUID (%i)' % message)
#return self.mailbox.getUid(message-1) #XXX: it seems that this method get uid and not message sequence number
log.debug(u"getUID (%i)" % message)
# return self.mailbox.getUid(message-1) #XXX: it seems that this method get uid and not message sequence number
return message
def getMessageCount(self):
"""Return the number of messages in this mailbox.
"""
log.debug('getMessageCount')
log.debug("getMessageCount")
ret = self.mailbox.getMessageCount()
log.debug("count = %i" % ret)
return ret
@ -196,26 +202,26 @@ class SatMailbox(object):
def getRecentCount(self):
"""Return the number of messages with the 'Recent' flag.
"""
log.debug('getRecentCount')
return len(self.mailbox.getMessageIdsWithFlag('\\Recent'))
log.debug("getRecentCount")
return len(self.mailbox.getMessageIdsWithFlag("\\Recent"))
def getUnseenCount(self):
"""Return the number of messages with the 'Unseen' flag.
"""
log.debug('getUnseenCount')
return self.getMessageCount() - len(self.mailbox.getMessageIdsWithFlag('\\SEEN'))
log.debug("getUnseenCount")
return self.getMessageCount() - len(self.mailbox.getMessageIdsWithFlag("\\SEEN"))
def isWriteable(self):
"""Get the read/write status of the mailbox.
@return: A true value if write permission is allowed, a false value otherwise.
"""
log.debug('isWriteable')
log.debug("isWriteable")
return True
def destroy(self):
"""Called before this mailbox is deleted, permanently.
"""
log.debug('destroy')
log.debug("destroy")
def requestStatus(self, names):
"""Return status information about this mailbox.
@ -227,7 +233,7 @@ class SatMailbox(object):
information up would be costly, a deferred whose callback will
eventually be passed this dictionary is returned instead.
"""
log.debug('requestStatus')
log.debug("requestStatus")
return imap4.statusRequestHelper(self, names)
def addListener(self, listener):
@ -237,7 +243,7 @@ class SatMailbox(object):
@param listener: An object to add to the set of those which will
be notified when the contents of this mailbox change.
"""
log.debug(u'addListener %s' % listener)
log.debug(u"addListener %s" % listener)
self.listeners.add(listener)
def removeListener(self, listener):
@ -250,11 +256,11 @@ class SatMailbox(object):
@raise ValueError: Raised when the given object is not a listener for
this mailbox.
"""
log.debug('removeListener')
log.debug("removeListener")
if listener in self.listeners:
self.listeners.remove(listener)
else:
raise imap4.MailboxException('Trying to remove an unknown listener')
raise imap4.MailboxException("Trying to remove an unknown listener")
def addMessage(self, message, flags=(), date=None):
"""Add the given message to this mailbox.
@ -265,7 +271,7 @@ class SatMailbox(object):
id if the message is added successfully and whose errback is
invoked otherwise.
"""
log.debug('addMessage')
log.debug("addMessage")
raise imap4.MailboxException("Client message addition not implemented yet")
def expunge(self):
@ -273,7 +279,7 @@ class SatMailbox(object):
@return: The list of message sequence numbers which were deleted,
or a Deferred whose callback will be invoked with such a list.
"""
log.debug('expunge')
log.debug("expunge")
self.mailbox.removeDeleted()
def fetch(self, messages, uid):
@ -282,16 +288,23 @@ class SatMailbox(object):
about
@param uid: If true, the IDs specified in the query are UIDs;
"""
log.debug(u'fetch (%s, %s)' % (messages, uid))
log.debug(u"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 is None:
log.debug('stopping iteration')
log.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:
@ -299,7 +312,14 @@ class SatMailbox(object):
for mess_idx in messages:
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.
@ -316,14 +336,16 @@ class SatMailbox(object):
been performed, or a Deferred whose callback will be invoked with
such a dict.
"""
log.debug('store')
log.debug("store")
flags = [flag.upper() for flag in flags]
def updateFlags(getF, setF):
ret = {}
for mess_id in messages:
if (uid and mess_id is 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:
@ -348,7 +370,7 @@ class SatMailbox(object):
ret = updateFlags(self.mailbox.getFlags, self.mailbox.setFlags)
newFlags = {}
for idx in ret:
#we have to convert idx to uid for the listeners
# we have to convert idx to uid for the listeners
newFlags[self.mailbox.getUid(idx)] = ret[idx]
for listener in self.listeners:
listener.flagsChanged(newFlags)
@ -359,18 +381,24 @@ class SatMailbox(object):
Flags with the \\ prefix are reserved for use as system flags.
@return: A list of the flags that can be set on messages in this mailbox.
"""
log.debug('getFlags')
return ['\\SEEN', '\\ANSWERED', '\\FLAGGED', '\\DELETED', '\\DRAFT'] # TODO: add '\\RECENT'
log.debug("getFlags")
return [
"\\SEEN",
"\\ANSWERED",
"\\FLAGGED",
"\\DELETED",
"\\DRAFT",
] # TODO: add '\\RECENT'
def getHierarchicalDelimiter(self):
"""Get the character which delimits namespaces for in this mailbox.
"""
log.debug('getHierarchicalDelimiter')
return '.'
log.debug("getHierarchicalDelimiter")
return "."
class ImapSatAccount(imap4.MemoryAccount):
#implements(imap4.IAccount)
# implements(imap4.IAccount)
def __init__(self, host, profile):
log.debug("ImapAccount init")
@ -378,7 +406,7 @@ class ImapSatAccount(imap4.MemoryAccount):
self.profile = profile
imap4.MemoryAccount.__init__(self, profile)
self.addMailbox("Inbox") # We only manage Inbox for the moment
log.debug('INBOX added')
log.debug("INBOX added")
def _emptyMailbox(self, name, id):
return SatMailbox(self.host, name, self.profile)
@ -391,8 +419,8 @@ class ImapRealm(object):
self.host = host
def requestAvatar(self, avatarID, mind, *interfaces):
log.debug('requestAvatar')
profile = avatarID.decode('utf-8')
log.debug("requestAvatar")
profile = avatarID.decode("utf-8")
if imap4.IAccount not in interfaces:
raise NotImplementedError
return imap4.IAccount, ImapSatAccount(self.host, profile), lambda: None
@ -404,16 +432,19 @@ class SatProfileCredentialChecker(object):
Check if the profile exists, and if the password is OK
Return the profile as avatarId
"""
implements(checkers.ICredentialsChecker)
credentialInterfaces = (credentials.IUsernamePassword,
credentials.IUsernameHashedPassword)
credentialInterfaces = (
credentials.IUsernamePassword,
credentials.IUsernameHashedPassword,
)
def __init__(self, host):
self.host = host
def _cbPasswordMatch(self, matched, profile):
if matched:
return profile.encode('utf-8')
return profile.encode("utf-8")
else:
return failure.Failure(cred_error.UnauthorizedLogin())
@ -421,7 +452,9 @@ class SatProfileCredentialChecker(object):
profiles = self.host.memory.getProfilesList()
if not credentials.username in profiles:
return defer.fail(cred_error.UnauthorizedLogin())
d = self.host.memory.asyncGetParamA("Password", "Connection", profile_key=credentials.username)
d = self.host.memory.asyncGetParamA(
"Password", "Connection", profile_key=credentials.username
)
d.addCallback(lambda password: credentials.checkPassword(password))
d.addCallback(self._cbPasswordMatch, credentials.username)
return d