From: Low Kian Seong Date: Thu, 9 Jan 2014 07:42:26 +0000 (+0800) Subject: clean up and violations removal X-Git-Tag: v0.3.6~1^2~1^2 X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=94db3284f9a5a414f46c566b1c3ef73d62f49bb9;p=flanker.git clean up and violations removal --- diff --git a/flanker/mime/__init__.py b/flanker/mime/__init__.py index 99bfaf4..1a3d3ad 100644 --- a/flanker/mime/__init__.py +++ b/flanker/mime/__init__.py @@ -23,10 +23,11 @@ not attempt to fix anything except simple errors (like mistyped charsets) Alternatives: -If you still need to process the broken MIME, use flanker.mime.fallback.FallbackMessage -that relies on python parser in terms of fixing the broken MIME and forces broken -encodings in bodies and headers, but beware that it can loose some information because -of broken or unknown encodings. +If you still need to process the broken MIME, use +flanker.mime.fallback.FallbackMessage that relies on python parser in terms +of fixing the broken MIME and forces broken encodings in bodies and headers, +but beware that it can loose some information because of broken +or unknown encodings. Examples ------- diff --git a/flanker/mime/bounce.py b/flanker/mime/bounce.py index 43aa9de..8deacb0 100644 --- a/flanker/mime/bounce.py +++ b/flanker/mime/bounce.py @@ -39,9 +39,11 @@ def get_status(headers): if RE_STATUS.match(v.strip()): return v + def get_notification(message): for part in message.walk(): - if part.headers.get('Content-Description', '').lower() == 'notification': + if part.headers.get('Content-Description', + '').lower() == 'notification': return part.body @@ -56,11 +58,10 @@ HEADERS = ('Action', RE_STATUS = re.compile(r'\d\.\d+\.\d+', re.IGNORECASE) + class Result(object): def __init__(self, score, status, notification, diagnostic_code): self.score = score self.status = status self.notification = notification self.diagnostic_code = diagnostic_code - - diff --git a/flanker/mime/create.py b/flanker/mime/create.py index 02cb37e..b30a1b5 100644 --- a/flanker/mime/create.py +++ b/flanker/mime/create.py @@ -7,6 +7,7 @@ from flanker.mime.message import scanner from flanker.mime.message.headers.parametrized import fix_content_type from flanker.mime.message.headers import WithParams + def multipart(subtype): return MimePart( container=Part( @@ -34,7 +35,8 @@ def text(subtype, body, charset=None, disposition=None, filename=None): is_root=True) -def binary(maintype, subtype, body, filename=None, disposition=None, charset=None): +def binary(maintype, subtype, body, filename=None, + disposition=None, charset=None): return MimePart( container=Body( content_type=ContentType(maintype, subtype), @@ -45,7 +47,8 @@ def binary(maintype, subtype, body, filename=None, disposition=None, charset=Non is_root=True) -def attachment(content_type, body, filename=None, disposition=None, charset=None): +def attachment(content_type, body, filename=None, + disposition=None, charset=None): """Smarter method to build attachments that detects the proper content type and form of the message based on content type string, body and filename of the attachment @@ -83,4 +86,3 @@ def from_python(message): def from_message(message): return from_string(message.to_string()) - diff --git a/flanker/mime/message/charsets.py b/flanker/mime/message/charsets.py index 2e6b4fc..9cd1333 100644 --- a/flanker/mime/message/charsets.py +++ b/flanker/mime/message/charsets.py @@ -2,6 +2,7 @@ import regex as re from flanker.mime.message import errors from flanker.utils import to_utf8, to_unicode + def convert_to_unicode(charset, value): #in case of unicode we have nothing to do if isinstance(value, unicode): @@ -11,6 +12,7 @@ def convert_to_unicode(charset, value): return to_unicode(value, charset=charset) + def _translate_charset(charset): """Translates crappy charset into Python analogue (if supported). @@ -31,4 +33,3 @@ def _translate_charset(charset): return 'utf-8' return charset - diff --git a/flanker/mime/message/errors.py b/flanker/mime/message/errors.py index 34f4d10..cc99be4 100644 --- a/flanker/mime/message/errors.py +++ b/flanker/mime/message/errors.py @@ -1,10 +1,12 @@ class MimeError(Exception): pass + class DecodingError(MimeError): """Thrown when there is an encoding error.""" pass + class EncodingError(MimeError): """Thrown when there is an decoding error.""" pass diff --git a/flanker/mime/message/fallback/create.py b/flanker/mime/message/fallback/create.py index a2d3354..ecc4f70 100644 --- a/flanker/mime/message/fallback/create.py +++ b/flanker/mime/message/fallback/create.py @@ -1,8 +1,10 @@ import email from flanker.mime.message.fallback.part import FallbackMimePart + def from_string(string): return FallbackMimePart(email.message_from_string(string)) + def from_python(message): return FallbackMimePart(message) diff --git a/flanker/mime/message/headers/encodedword.py b/flanker/mime/message/headers/encodedword.py index 9f5eeb9..e218e1f 100644 --- a/flanker/mime/message/headers/encodedword.py +++ b/flanker/mime/message/headers/encodedword.py @@ -1,5 +1,6 @@ # coding:utf-8 -import logging, regex as re +import logging +import regex as re import email.quoprimime import email.base64mime @@ -13,6 +14,7 @@ log = logging.getLogger(__name__) #deal with unfolding foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)") + def unfold(value): """ Unfolding is accomplished by simply removing any CRLF @@ -42,7 +44,7 @@ def mime_to_unicode(header): """ try: header = unfold(header) - decoded = [] # decoded parts + decoded = [] # decoded parts while header: match = encodedWord.search(header) @@ -70,7 +72,7 @@ def mime_to_unicode(header): try: log.warning( u"HEADER-DECODE-FAIL: ({0}) - b64encoded".format( - b64encode(header))) + b64encode(header))) except Exception: log.exception("Failed to log exception") return header @@ -115,6 +117,3 @@ def decode_part(charset, encoding, value): else: raise errors.DecodingError( "Unknown encoding: {0}".format(encoding)) - - - diff --git a/flanker/mime/message/headers/encoding.py b/flanker/mime/message/headers/encoding.py index 8414a90..737cddd 100644 --- a/flanker/mime/message/headers/encoding.py +++ b/flanker/mime/message/headers/encoding.py @@ -12,11 +12,12 @@ log = logging.getLogger(__name__) # max length for a header line is 80 chars # max recursion depth is 1000 # 80 * 1000 for header is too much for the system -# so we allow just 100 lines for header +# so we allow just 100 lines for header MAX_HEADER_LENGTH = 8000 ADDRESS_HEADERS = ('From', 'To', 'Delivered-To', 'Cc', 'Bcc', 'Reply-To') + def to_mime(key, value): if not value: return "" @@ -44,15 +45,15 @@ def encode_unstructured(name, value): return to_utf8(value) try: return Header( - value.encode("ascii"), "ascii", header_name=name).encode( - splitchars=' ;,') + value.encode("ascii"), "ascii", + header_name=name).encode(splitchars=' ;,') except UnicodeEncodeError: if is_address_header(name, value): return encode_address_header(name, value) else: return Header( - to_utf8(value), "utf-8", header_name=name).encode( - splitchars=' ;,') + to_utf8(value), "utf-8", + header_name=name).encode(splitchars=' ;,') def encode_address_header(name, value): @@ -75,18 +76,17 @@ def encode_param(key, name, value): value = value.encode("ascii") return email.message._formatparam(name, value) except Exception: - value = Header( - value.encode("utf-8"), "utf-8", header_name=key).encode(splitchars=' ;,') + value = Header(value.encode("utf-8"), "utf-8", header_name=key).encode(splitchars=' ;,') return email.message._formatparam(name, value) def encode_string(name, value): try: return Header( - value.encode("ascii"), "ascii", header_name=name).encode(splitchars=' ;,') + value.encode("ascii"), "ascii", + header_name=name).encode(splitchars=' ;,') except UnicodeEncodeError: - return Header( - value.encode("utf-8"), "utf-8", header_name=name).encode(splitchars=' ;,') + return Header(value.encode("utf-8"), "utf-8", header_name=name).encode(splitchars=' ;,') def is_address_header(key, val): diff --git a/flanker/mime/message/headers/headers.py b/flanker/mime/message/headers/headers.py index 784b3d0..57f0248 100644 --- a/flanker/mime/message/headers/headers.py +++ b/flanker/mime/message/headers/headers.py @@ -64,6 +64,7 @@ class MimeHeaders(object): """ changed = [False] + def tracking_fn(key, val): new_key, new_val = fn(key, val) if new_val != val or new_key != key: @@ -75,21 +76,18 @@ class MimeHeaders(object): self.v = v self.changed = True - def items(self): """ Returns header,val pairs in the preserved order. """ return list(self.iteritems()) - def iteritems(self): """ Returns iterator header,val pairs in the preserved order. """ return self.v.iteritems() - def get(self, key, default=None): """ Returns header value (case-insensitive). diff --git a/flanker/mime/message/headers/parametrized.py b/flanker/mime/message/headers/parametrized.py index 9ec8269..e3a8280 100644 --- a/flanker/mime/message/headers/parametrized.py +++ b/flanker/mime/message/headers/parametrized.py @@ -182,6 +182,7 @@ def partition(parts): if encoded: yield join_parameters(encoded) + def decode_charset(parameter): """Decodes things like: "us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20" @@ -207,27 +208,34 @@ def parameter(ptype, key, value): """ return (ptype, key, value) + def is_quoted(part): return get_value(part)[0] == '"' + def is_new_style(parameter): return parameter[0] == 'new' + def is_old_style(parameter): return parameter[0] == 'old' + def is_encoded(part): return part[1][2] == '*' + def get_key(parameter): if is_old_style(parameter): return parameter[1].lower() else: return parameter[1][0].lower() + def get_value(parameter): return parameter[2] + def join_parameters(parts): joined = "".join(get_value(p) for p in parts) for p in parts: diff --git a/flanker/mime/message/headers/parsing.py b/flanker/mime/message/headers/parsing.py index 5be3d60..500696b 100644 --- a/flanker/mime/message/headers/parsing.py +++ b/flanker/mime/message/headers/parsing.py @@ -20,6 +20,7 @@ def parse_stream(stream): out.append(parse_header(header)) return out + def parse_header(header): """ Accepts a raw header with name, colons and newlines and returns it's parsed value @@ -29,6 +30,7 @@ def parse_header(header): raise DecodingError("Non-ascii header name") return name, parse_header_value(name, encodedword.unfold(val)) + def parse_header_value(name, val): if not is_pure_ascii(val): if parametrized.is_parametrized(name, val): @@ -48,12 +50,14 @@ def parse_header_value(name, val): else: return val + def is_empty(line): return line in ('\r\n', '\r', '\n') RE_HEADER = regex.compile(r'^(From |[\041-\071\073-\176]+:|[\t ])') + def split(fp): """Read lines with headers until the start of body""" lines = deque() @@ -121,4 +125,3 @@ def split2(header): return normalize(pair[0].rstrip()), pair[1].lstrip() else: return (None, None) - diff --git a/flanker/mime/message/headers/wrappers.py b/flanker/mime/message/headers/wrappers.py index f5d8a24..618d9eb 100644 --- a/flanker/mime/message/headers/wrappers.py +++ b/flanker/mime/message/headers/wrappers.py @@ -48,7 +48,6 @@ class ContentType(tuple): def subtype(self): return tuple.__getitem__(self, 0).split('/')[1] - def is_content_type(self): return True @@ -91,7 +90,7 @@ class ContentType(tuple): return self == 'message/feedback-report' def is_delivery_report(self): - return self == 'multipart/report' + return self == 'multipart/report' def get_boundary(self): return self.params.get("boundary") @@ -135,7 +134,7 @@ class MessageId(str): return str.__new__(cls, *args, **kw) def __clean(self): - return self.replace('"','').replace("'", '') + return self.replace('"', '').replace("'", '') def __hash__(self): return hash(self.__clean()) @@ -182,4 +181,3 @@ class Subject(unicode): def strip_replies(self): return self.RE_RE.sub('', self) -