PEP8 fixes

This commit is contained in:
Antoine Nguyen
2015-01-16 10:24:15 +01:00
parent 46128fa61f
commit 38649a614f
12 changed files with 104 additions and 65 deletions
+2 -1
View File
@@ -13,7 +13,8 @@ class ParametersForm(AdminParametersForm):
max_attachment_size = forms.CharField(
label=_("Maximum attachment size"),
initial="2048",
help_text=_("Maximum attachment size in bytes (or KB, MB, GB if specified)")
help_text=_(
"Maximum attachment size in bytes (or KB, MB, GB if specified)")
)
sep1 = SeparatorField(label=_("IMAP settings"))
+2
View File
@@ -25,6 +25,7 @@ class WebmailInternalError(InternalError):
class UnknownAction(ModoboaException):
"""
Use this exception when the webmail encounter an unknown action.
"""
@@ -35,6 +36,7 @@ class UnknownAction(ModoboaException):
class ImapError(ModoboaException):
def __init__(self, reason):
self.reason = reason
+4 -3
View File
@@ -169,8 +169,8 @@ class ComposeMailForm(forms.Form):
class ForwardMailForm(ComposeMailForm):
"""Forward mail form.
"""
"""Forward mail form."""
def _build_msg(self, request):
"""Convert form's content to a MIME message.
@@ -203,7 +203,8 @@ class FolderForm(forms.Form):
widget=forms.HiddenInput(attrs={"class": "form-control"}),
required=False
)
name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}))
name = forms.CharField(
widget=forms.TextInput(attrs={"class": "form-control"}))
class AttachmentForm(forms.Form):
@@ -80,18 +80,19 @@ def create_mail_attachment(attdef, payload=None):
res = MIMEBase(maintype, subtype)
if payload is None:
with open(os.path.join(
settings.MEDIA_ROOT, "webmail", attdef["tmpname"]), "rb") as fp:
settings.MEDIA_ROOT, "webmail", attdef["tmpname"]), "rb") as fp:
res.set_payload(fp.read())
else:
res.set_payload(payload)
Encoders.encode_base64(res)
if type(attdef['fname']) is str:
if isinstance(attdef['fname'], str):
attdef['fname'] = attdef['fname'].decode('utf-8')
res['Content-Disposition'] = build_header(attdef['fname'])
return res
class AttachmentUploadHandler(FileUploadHandler):
"""
Simple upload handler to limit the size of the attachments users
can upload.
+16 -8
View File
@@ -10,16 +10,19 @@ retrieve multiple attributes of a message.
This simple module tries to fix that *problem*.
"""
class ParseError(Exception):
pass
class Token(object):
def __init__(self, value):
self.value = value
class Literal(Token):
def __init__(self, value):
super(Literal, self).__init__(value)
self.next_token_len = int(self.value[1:-1])
@@ -50,7 +53,8 @@ def parse_next_token(buf):
end = pos - 1
break
if end == -1:
raise ParseError("End of buffer reached while looking for a token end")
raise ParseError(
"End of buffer reached while looking for a token end")
end += 1
token = klass(buf[:end])
return token, end
@@ -94,7 +98,7 @@ def parse_bodystructure(buf, depth=0, prefix=""):
# make a difference between a content-disposition with
# multiple args beeing parsed and a mime part! (see
# the last example at the end of the file)
if type(ret[0]) == list or len(ret) >= 7:
if isinstance(ret[0], list) or len(ret) >= 7:
partnum = prefix
if partnum is not None:
return [{"partnum": partnum, "struct": ret}], pos
@@ -111,7 +115,8 @@ def parse_bodystructure(buf, depth=0, prefix=""):
else:
ret.append(token.value.strip('"'))
raise ParseError("End of buffer reached while looking for a BODY/BODYSTRUCTURE end")
raise ParseError(
"End of buffer reached while looking for a BODY/BODYSTRUCTURE end")
def parse_fetch_response(data):
@@ -128,7 +133,7 @@ def parse_fetch_response(data):
while cpt < len(data):
content = ()
while cpt < len(data) and data[cpt] != ')':
if type(data[cpt]) == str:
if isinstance(data[cpt], str):
# FIXME : probably an unsolicited response
cpt += 1
continue
@@ -192,13 +197,13 @@ def parse_fetch_response(data):
def dump_bodystructure(bs, depth=0):
if depth:
print " " * (depth * 4),
if type(bs[0]) == dict:
if isinstance(bs[0], dict):
print "%s :" % bs[0]["partnum"],
struct = bs[0]["struct"]
else:
struct = bs
if type(struct[0]) == list:
if isinstance(struct[0], list):
print "multipart/%s" % struct[1]
for part in struct[0]:
dump_bodystructure(part, depth + 1)
@@ -207,11 +212,14 @@ def dump_bodystructure(bs, depth=0):
if __name__ == "__main__":
# resp = [('855 (UID 46931 BODYSTRUCTURE ((("text" "plain" ("charset" "iso-8859-1") NIL NIL "quoted-printable" 886 32 NIL NIL NIL NIL)("text" "html" ("charset" "us-ascii") NIL NIL "quoted-printable" 1208 16 NIL NIL NIL NIL) "alternative" ("boundary" "----=_NextPart_001_0003_01CCC564.B2F64FF0") NIL NIL NIL)("application" "octet-stream" ("name" "Carte Verte_2.pdf") NIL NIL "base64" 285610 NIL ("attachment" ("filename" "Carte Verte_2.pdf")) NIL NIL) "mixed" ("boundary" "----=_NextPart_000_0002_01CCC564.B2F64FF0") NIL NIL NIL) BODY[HEADER.FIELDS (DATE FROM TO CC SUBJECT)] {153}', 'From: <Service.client10@maaf.fr>\r\nTo: <TONIO@NGYN.ORG>\r\nCc: \r\nSubject: Notre contact du 28/12/2011 - 192175092\r\nDate: Wed, 28 Dec 2011 13:29:17 +0100\r\n\r\n'), ')']
# resp = [('855 (UID 46931 BODYSTRUCTURE ((("text" "plain" ("charset" "iso-8859-1") NIL NIL "quoted-printable" 886 32 NIL NIL NIL NIL)("text" "html" ("charset" "us-ascii") NIL NIL "quoted-printable" 1208 16 NIL NIL NIL NIL) "alternative" ("boundary" "----=_NextPart_001_0003_01CCC564.B2F64FF0") NIL NIL NIL)("application" "octet-stream" ("name" "Carte Verte_2.pdf") NIL NIL "base64" 285610 NIL ("attachment" ("filename" "Carte Verte_2.pdf")) NIL NIL) "mixed" ("boundary" "----=_NextPart_000_0002_01CCC564.B2F64FF0") NIL NIL NIL) BODY[HEADER.FIELDS (DATE FROM TO CC SUBJECT)] {153}', 'From: <Service.client10@maaf.fr>\r\nTo: <TONIO@NGYN.ORG>\r\nCc: \r\nSubject: Notre contact du 28/12/2011 - 192175092\r\nDate: Wed, 28 Dec 2011 13:29:17 +0100\r\n\r\n'), ')']
# #resp = [('856 (UID 46936 BODYSTRUCTURE (("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 724 22 NIL NIL NIL NIL)("text" "html" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 2662 48 NIL NIL NIL NIL) "alternative" ("boundary" "----=_Part_1326887_254624357.1325083973970") NIL NIL NIL) BODY[HEADER.FIELDS (DATE FROM TO CC SUBJECT)] {258}', 'Date: Wed, 28 Dec 2011 15:52:53 +0100 (CET)\r\nFrom: =?ISO-8859-1?Q?Malakoff_M=E9d=E9ric?= <communication@communication.malakoffmederic.com>\r\nTo: Antoine Nguyen <tonio@ngyn.org>\r\nSubject: =?ISO-8859-1?Q?Votre_inscription_au_grand_Jeu_Malakoff_M=E9d=E9ric?=\r\n\r\n'), ')']
resp = [('856 (UID 11111 BODYSTRUCTURE ((("text" "plain" ("charset" "UTF-8") NIL NIL "7bit" 0 0 NIL NIL NIL NIL) "mixed" ("boundary" "----=_Part_407172_3159001.1321948277321") NIL NIL NIL)("application" "octet-stream" ("name" "26274308.pdf") NIL NIL "base64" 14906 NIL ("attachment" ("filename" "26274308.pdf")) NIL NIL) "mixed" ("boundary" "----=_Part_407171_9686991.1321948277321") NIL NIL NIL)',), ')']
resp = [
('856 (UID 11111 BODYSTRUCTURE ((("text" "plain" ("charset" "UTF-8") NIL NIL "7bit" 0 0 NIL NIL NIL NIL) "mixed" ("boundary" "----=_Part_407172_3159001.1321948277321") NIL NIL NIL)("application" "octet-stream" ("name" "26274308.pdf") NIL NIL "base64" 14906 NIL ("attachment" ("filename" "26274308.pdf")) NIL NIL) "mixed" ("boundary" "----=_Part_407171_9686991.1321948277321") NIL NIL NIL)',
),
')']
# resp = [('19 (UID 19 FLAGS (\\Seen) BODYSTRUCTURE (("text" "plain" ("charset" "ISO-8859-1" "format" "flowed") NIL NIL "7bit" 2 1 NIL NIL NIL NIL)("message" "rfc822" ("name*" "ISO-8859-1\'\'%5B%49%4E%53%43%52%49%50%54%49%4F%4E%5D%20%52%E9%63%E9%70%74%69%6F%6E%20%64%65%20%76%6F%74%72%65%20%64%6F%73%73%69%65%72%20%64%27%69%6E%73%63%72%69%70%74%69%6F%6E%20%46%72%65%65%20%48%61%75%74%20%44%E9%62%69%74") NIL NIL "8bit" 3632 ("Wed, 13 Dec 2006 20:30:02 +0100" {70}',
# "[INSCRIPTION] R\xe9c\xe9ption de votre dossier d'inscription Free Haut D\xe9bit"),
+2 -2
View File
@@ -82,7 +82,7 @@ class ImapEmail(Email):
)
self.bs = BodyStructure(self._msg['BODYSTRUCTURE'])
self._find_attachments()
if not self.dformat in ["plain", "html"]:
if self.dformat not in ["plain", "html"]:
self.dformat = parameters.get_user(
self.request.user, self.dformat
)
@@ -312,7 +312,7 @@ class ForwardModifier(Modifier):
return "----- %s -----" % _("Original message")
def _header_begin_html(self):
return "----- %s -----" % _("Original message")
return "----- %s -----" % _("Original message")
def _header_line_plain(self, key, value):
return "%s: %s\n" % (key, value)
+1 -2
View File
@@ -13,7 +13,7 @@ __all__ = [
def to_unicode(value):
"""Try to convert a string to unicode.
"""
if value is None or type(value) is unicode:
if value is None or isinstance(value, unicode):
return value
try:
value = value.decode('utf-8')
@@ -111,4 +111,3 @@ def parse_subject(value, **kwargs):
except UnicodeDecodeError:
subject = value
return to_unicode(subject)
+58 -36
View File
@@ -3,24 +3,27 @@
:mod:`imaputils` --- Extra IMAPv4 utilities
-------------------------------------------
"""
import imaplib
import ssl
import email
import imaplib
import re
import ssl
import time
from functools import wraps
from django.utils.translation import ugettext as _
from modoboa.lib import parameters, imap_utf7
from modoboa.lib.exceptions import InternalError
from modoboa.lib.connections import ConnectionsManager
from modoboa.lib.web_utils import static_url
from ..exceptions import ImapError, WebmailInternalError
from .fetch_parser import parse_fetch_response
from modoboa.lib import parameters
from modoboa.lib.connections import ConnectionsManager
from modoboa.lib.exceptions import InternalError
#imaplib.Debug = 4
# imaplib.Debug = 4
class capability(object):
"""
Simple decorator to check if the server presents the required
capability. If not, a fallback method is called instead.
@@ -28,6 +31,7 @@ class capability(object):
:param name: the capability name (upper case)
:param fallback_method: a method's name
"""
def __init__(self, name, fallback_method):
self.name = name
self.fallback_method = fallback_method
@@ -43,12 +47,14 @@ class capability(object):
class BodyStructure(object):
"""
BODYSTRUCTURE response parser.
Just a simple class that tries to distinguish content parts from
attachments.
"""
def __init__(self, definition=None):
self.is_multipart = False
self.contents = {}
@@ -71,7 +77,8 @@ class BodyStructure(object):
* If the MIME type is text/plain or text/html:
* If no previous part of this type has already been seen, it's a content
* If no previous part of this type has already been seen,
it's a content
* Otherwise it's an attachment
* Else, if the multipart subtype is related, we consider this
@@ -82,6 +89,7 @@ class BodyStructure(object):
:param definition: a part definition (list)
:param pnum: the part's number
:param multisubtype: the multipart subtype
"""
pnum = "1" if pnum is None else pnum
params = dict(pnum=pnum, params=definition[2], cid=definition[3],
@@ -91,7 +99,7 @@ class BodyStructure(object):
subtype = definition[1].lower()
ftype = "%s/%s" % (definition[0].lower(), subtype)
if ftype in ("text/plain", "text/html"):
if not subtype in self.contents:
if subtype not in self.contents:
self.contents[subtype] = [params]
else:
self.contents[subtype].append(params)
@@ -106,24 +114,27 @@ class BodyStructure(object):
if mtype == "text":
extensions = ["textlines"] + extensions
elif ftype == "message/rfc822":
extensions = ["envelopestruct", "bodystruct", "textlines"] + extensions
extensions = [
"envelopestruct",
"bodystruct",
"textlines"] + extensions
for idx, value in enumerate(definition[7:]):
params[extensions[idx]] = value
self.attachments += [params]
def load_from_definition(self, definition, multisubtype=None):
if type(definition) == dict:
if isinstance(definition, dict):
struct = definition["struct"]
pnum = definition["partnum"]
elif type(definition[0]) == dict:
elif isinstance(definition[0], dict):
struct = definition[0]["struct"]
pnum = definition[0]["partnum"]
else:
struct = definition
pnum = None
if type(struct[0]) == list:
if isinstance(struct[0], list):
for part in struct[0]:
self.load_from_definition(part, struct[1])
return
@@ -146,8 +157,11 @@ class IMAPconnector(object):
__metaclass__ = ConnectionsManager
list_base_pattern = r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" "?(?P<name>[^"]*)"?'
list_response_pattern_literal = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" \{(?P<namelen>\d+)\}')
list_base_pattern = (
r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" "?(?P<name>[^"]*)"?'
)
list_response_pattern_literal = re.compile(
r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" \{(?P<namelen>\d+)\}')
list_response_pattern = re.compile(list_base_pattern)
listextended_response_pattern = \
re.compile(list_base_pattern + r'\s*(?P<childinfo>.*)')
@@ -178,7 +192,7 @@ class IMAPconnector(object):
if name in ['FETCH', 'SORT', 'STORE', 'COPY', 'SEARCH']:
try:
typ, data = self.m.uid(name, *args)
except imaplib.IMAP4.error, e:
except imaplib.IMAP4.error as e:
raise ImapError(e)
if typ == "NO":
raise ImapError(data)
@@ -188,17 +202,17 @@ class IMAPconnector(object):
try:
typ, data = self.m._simple_command(name, *args)
except imaplib.IMAP4.error, e:
except imaplib.IMAP4.error as e:
raise ImapError(e)
if typ == "NO":
raise ImapError(data)
if not 'responses' in kwargs:
if not name in self.m.untagged_responses:
if 'responses' not in kwargs:
if name not in self.m.untagged_responses:
return None
return self.m.untagged_responses.pop(name)
res = []
for r in kwargs['responses']:
if not r in self.m.untagged_responses:
if r not in self.m.untagged_responses:
return None
res.append(self.m.untagged_responses.pop(r))
return res
@@ -218,14 +232,20 @@ class IMAPconnector(object):
if type(bodystruct[0]) in [list, tuple]:
cpt = 1
for part in bodystruct[0]:
nprefix = "%s" % cpt if prefix == "" else "%s.%d" % (prefix, cpt)
nprefix = "%s" % cpt if prefix == "" else "%s.%d" % (
prefix, cpt)
index, encoding, size = \
self.__find_content_in_bodystruct(part, mtype, stype, nprefix)
self.__find_content_in_bodystruct(
part,
mtype,
stype,
nprefix)
if index is not None:
return (index, encoding, size)
cpt += 1
else:
if bodystruct[0].lower() == mtype and bodystruct[1].lower() == stype:
if bodystruct[0].lower() == mtype and \
bodystruct[1].lower() == stype:
return ("1" if not len(prefix) else prefix,
bodystruct[5], int(bodystruct[6]))
return (None, None, 0)
@@ -275,9 +295,9 @@ class IMAPconnector(object):
"""
import socket
if type(user) is unicode:
if isinstance(user, unicode):
user = user.encode("utf-8")
if type(passwd) is unicode:
if isinstance(passwd, unicode):
passwd = passwd.encode("utf-8")
try:
secured = parameters.get_admin("IMAP_SECURED")
@@ -285,7 +305,7 @@ class IMAPconnector(object):
self.m = imaplib.IMAP4_SSL(self.address, self.port)
else:
self.m = imaplib.IMAP4(self.address, self.port)
except (socket.error, imaplib.IMAP4.error, ssl.SSLError), error:
except (socket.error, imaplib.IMAP4.error, ssl.SSLError) as error:
raise ImapError(_("Connection to IMAP server failed: %s" % error))
data = self._cmd("LOGIN", user, passwd)
@@ -320,9 +340,9 @@ class IMAPconnector(object):
if criterion == u"both":
criterion = u"from_addr, subject"
criterions = ""
if type(pattern) is unicode:
if isinstance(pattern, unicode):
pattern = pattern.encode("utf-8")
if type(criterion) is unicode:
if isinstance(criterion, unicode):
criterion = criterion.encode("utf-8")
for c in criterion.split(','):
if c == "from_addr":
@@ -418,12 +438,14 @@ class IMAPconnector(object):
return True
def _listmboxes_simple(self, topmailbox='INBOX', mailboxes=None, **kwargs):
#data = self._cmd("LIST", "", "*")
if not mailboxes: mailboxes = []
# data = self._cmd("LIST", "", "*")
if not mailboxes:
mailboxes = []
(status, data) = self.m.list()
newmboxes = []
for mb in data:
flags, delimiter, name = self.list_response_pattern.match(mb).groups()
flags, delimiter, name = self.list_response_pattern.match(
mb).groups()
name = name.strip('"').decode("imap4-utf-7")
mdm_found = False
for idx, mdm in enumerate(mailboxes):
@@ -437,7 +459,7 @@ class IMAPconnector(object):
if re.search("\%s" % delimiter, name):
parts = name.split(delimiter)
if not "path" in descr:
if "path" not in descr:
descr["path"] = parts[0]
descr["sub"] = []
if self._parse_mailbox_name(descr["sub"], parts[0], delimiter,
@@ -480,7 +502,7 @@ class IMAPconnector(object):
descr = dict(name=name)
newmboxes += [descr]
if r'\Marked' in flags or not r'\UnMarked' in flags:
if r'\Marked' in flags or r'\UnMarked' not in flags:
descr["send_status"] = True
if r'\HasChildren' in flags:
if r'\NonExistent' in flags:
@@ -529,7 +551,7 @@ class IMAPconnector(object):
if unseen_messages:
for mb in md_mailboxes:
if not "send_status" in mb:
if "send_status" not in mb:
continue
del mb["send_status"]
key = "path" if "path" in mb else "name"
@@ -631,7 +653,7 @@ class IMAPconnector(object):
We also compute the current usage.
"""
if not "QUOTA" in self.capabilities:
if "QUOTA" not in self.capabilities:
self.quota_limit = self.quota_current = None
return
@@ -700,7 +722,7 @@ class IMAPconnector(object):
data[int(uid)]['BODY[HEADER.FIELDS (DATE FROM TO CC SUBJECT)]']
)
msg['imapid'] = uid
if not r'\Seen' in data[int(uid)]['FLAGS']:
if r'\Seen' not in data[int(uid)]['FLAGS']:
msg['style'] = 'unseen'
if r'\Answered' in data[int(uid)]['FLAGS']:
msg['answered'] = True
@@ -3,10 +3,12 @@ from modoboa.lib import parameters
class EmailSignature(object):
"""User signature
:param user: User object
"""
def __init__(self, user):
self._sig = u""
dformat = parameters.get_user(user, "EDITOR")
+2
View File
@@ -24,9 +24,11 @@ def decode_payload(encoding, payload):
class WebmailNavigationParameters(NavigationParameters):
"""
Specific NavigationParameters subclass for the webmail.
"""
def __init__(self, request, defmailbox=None):
super(WebmailNavigationParameters, self).__init__(
request, 'webmail_navparams'
@@ -36,14 +36,14 @@ def viewmail_menu(selection, folder, user, mail_id=None):
"url": "action=forward&mbox=%s&mailid=%s" % (folder, mail_id),
"img": "fa fa-mail-forward",
"label": _("Forward")},
]},
]},
{"name": "delete",
"img": "fa fa-trash",
"class": "btn-danger",
"url": "{0}?mbox={1}&selection[]={2}".format(
reverse("webmail:mail_delete"), folder, mail_id),
"title": _("Delete")
},
},
{"name": "display_options",
"title": _("Display options"),
"img": "fa fa-cog",
@@ -150,7 +150,8 @@ def print_mailboxes(
extra_attrs = ' data-toggle="%d"' % mbox["unseen"]
if "sub" in mbox:
if selected is not None and selected != name and selected.count(name):
if selected is not None and selected != name and selected.count(
name):
ul_state = "visible"
div_state = "expanded"
else:
@@ -171,7 +172,7 @@ def print_mailboxes(
result += "<ul name='%s' class='nav nav-pills nav-stacked %s'>" % (
mbox["path"], ul_state) + print_mailboxes(
mbox["sub"], selected, withunseen, selectonly, hdelimiter
) + "</ul>\n"
) + "</ul>\n"
result += "</li>\n"
return result
+7 -7
View File
@@ -71,7 +71,7 @@ def getattachment(request):
@needs_mailbox()
def move(request):
for arg in ["msgset", "to"]:
if not arg in request.GET:
if arg not in request.GET:
raise BadRequest(_("Invalid request"))
mbc = get_imapconnector(request)
navparams = WebmailNavigationParameters(request)
@@ -291,8 +291,8 @@ def attachments(request, tplname="webmail/attachments.html"):
@login_required
@needs_mailbox()
def delattachment(request):
if not "compose_mail" in request.session \
or not "name" in request.GET \
if "compose_mail" not in request.session \
or "name" not in request.GET \
or not request.GET["name"]:
return ajax_response(request, "ko", respmsg=_("Bad query"))
@@ -305,7 +305,7 @@ def delattachment(request):
)
try:
os.remove(fullpath)
except OSError, e:
except OSError as e:
error = _("Failed to remove attachment: ") + str(e)
break
request.session.modified = True
@@ -390,11 +390,11 @@ def render_compose(request, form, posturl, email=None, insert_signature=False):
signature = EmailSignature(request.user)
body += unicode(signature)
randid = None
if not "id" in request.GET:
if "id" not in request.GET:
if "compose_mail" in request.session:
clean_attachments(request.session["compose_mail"]["attachments"])
randid = set_compose_session(request)
elif not "compose_mail" in request.session \
elif "compose_mail" not in request.session \
or request.session["compose_mail"]["id"] != request.GET["id"]:
randid = set_compose_session(request)
@@ -567,7 +567,7 @@ def index(request):
"""
action = request.GET.get("action", None)
if action is not None:
if not action in globals():
if action not in globals():
raise UnknownAction
response = globals()[action](request)
else: