jpayne@68: import binascii jpayne@68: import email.charset jpayne@68: import email.message jpayne@68: import email.errors jpayne@68: from email import quoprimime jpayne@68: jpayne@68: class ContentManager: jpayne@68: jpayne@68: def __init__(self): jpayne@68: self.get_handlers = {} jpayne@68: self.set_handlers = {} jpayne@68: jpayne@68: def add_get_handler(self, key, handler): jpayne@68: self.get_handlers[key] = handler jpayne@68: jpayne@68: def get_content(self, msg, *args, **kw): jpayne@68: content_type = msg.get_content_type() jpayne@68: if content_type in self.get_handlers: jpayne@68: return self.get_handlers[content_type](msg, *args, **kw) jpayne@68: maintype = msg.get_content_maintype() jpayne@68: if maintype in self.get_handlers: jpayne@68: return self.get_handlers[maintype](msg, *args, **kw) jpayne@68: if '' in self.get_handlers: jpayne@68: return self.get_handlers[''](msg, *args, **kw) jpayne@68: raise KeyError(content_type) jpayne@68: jpayne@68: def add_set_handler(self, typekey, handler): jpayne@68: self.set_handlers[typekey] = handler jpayne@68: jpayne@68: def set_content(self, msg, obj, *args, **kw): jpayne@68: if msg.get_content_maintype() == 'multipart': jpayne@68: # XXX: is this error a good idea or not? We can remove it later, jpayne@68: # but we can't add it later, so do it for now. jpayne@68: raise TypeError("set_content not valid on multipart") jpayne@68: handler = self._find_set_handler(msg, obj) jpayne@68: msg.clear_content() jpayne@68: handler(msg, obj, *args, **kw) jpayne@68: jpayne@68: def _find_set_handler(self, msg, obj): jpayne@68: full_path_for_error = None jpayne@68: for typ in type(obj).__mro__: jpayne@68: if typ in self.set_handlers: jpayne@68: return self.set_handlers[typ] jpayne@68: qname = typ.__qualname__ jpayne@68: modname = getattr(typ, '__module__', '') jpayne@68: full_path = '.'.join((modname, qname)) if modname else qname jpayne@68: if full_path_for_error is None: jpayne@68: full_path_for_error = full_path jpayne@68: if full_path in self.set_handlers: jpayne@68: return self.set_handlers[full_path] jpayne@68: if qname in self.set_handlers: jpayne@68: return self.set_handlers[qname] jpayne@68: name = typ.__name__ jpayne@68: if name in self.set_handlers: jpayne@68: return self.set_handlers[name] jpayne@68: if None in self.set_handlers: jpayne@68: return self.set_handlers[None] jpayne@68: raise KeyError(full_path_for_error) jpayne@68: jpayne@68: jpayne@68: raw_data_manager = ContentManager() jpayne@68: jpayne@68: jpayne@68: def get_text_content(msg, errors='replace'): jpayne@68: content = msg.get_payload(decode=True) jpayne@68: charset = msg.get_param('charset', 'ASCII') jpayne@68: return content.decode(charset, errors=errors) jpayne@68: raw_data_manager.add_get_handler('text', get_text_content) jpayne@68: jpayne@68: jpayne@68: def get_non_text_content(msg): jpayne@68: return msg.get_payload(decode=True) jpayne@68: for maintype in 'audio image video application'.split(): jpayne@68: raw_data_manager.add_get_handler(maintype, get_non_text_content) jpayne@68: jpayne@68: jpayne@68: def get_message_content(msg): jpayne@68: return msg.get_payload(0) jpayne@68: for subtype in 'rfc822 external-body'.split(): jpayne@68: raw_data_manager.add_get_handler('message/'+subtype, get_message_content) jpayne@68: jpayne@68: jpayne@68: def get_and_fixup_unknown_message_content(msg): jpayne@68: # If we don't understand a message subtype, we are supposed to treat it as jpayne@68: # if it were application/octet-stream, per jpayne@68: # tools.ietf.org/html/rfc2046#section-5.2.4. Feedparser doesn't do that, jpayne@68: # so do our best to fix things up. Note that it is *not* appropriate to jpayne@68: # model message/partial content as Message objects, so they are handled jpayne@68: # here as well. (How to reassemble them is out of scope for this comment :) jpayne@68: return bytes(msg.get_payload(0)) jpayne@68: raw_data_manager.add_get_handler('message', jpayne@68: get_and_fixup_unknown_message_content) jpayne@68: jpayne@68: jpayne@68: def _prepare_set(msg, maintype, subtype, headers): jpayne@68: msg['Content-Type'] = '/'.join((maintype, subtype)) jpayne@68: if headers: jpayne@68: if not hasattr(headers[0], 'name'): jpayne@68: mp = msg.policy jpayne@68: headers = [mp.header_factory(*mp.header_source_parse([header])) jpayne@68: for header in headers] jpayne@68: try: jpayne@68: for header in headers: jpayne@68: if header.defects: jpayne@68: raise header.defects[0] jpayne@68: msg[header.name] = header jpayne@68: except email.errors.HeaderDefect as exc: jpayne@68: raise ValueError("Invalid header: {}".format( jpayne@68: header.fold(policy=msg.policy))) from exc jpayne@68: jpayne@68: jpayne@68: def _finalize_set(msg, disposition, filename, cid, params): jpayne@68: if disposition is None and filename is not None: jpayne@68: disposition = 'attachment' jpayne@68: if disposition is not None: jpayne@68: msg['Content-Disposition'] = disposition jpayne@68: if filename is not None: jpayne@68: msg.set_param('filename', jpayne@68: filename, jpayne@68: header='Content-Disposition', jpayne@68: replace=True) jpayne@68: if cid is not None: jpayne@68: msg['Content-ID'] = cid jpayne@68: if params is not None: jpayne@68: for key, value in params.items(): jpayne@68: msg.set_param(key, value) jpayne@68: jpayne@68: jpayne@68: # XXX: This is a cleaned-up version of base64mime.body_encode (including a bug jpayne@68: # fix in the calculation of unencoded_bytes_per_line). It would be nice to jpayne@68: # drop both this and quoprimime.body_encode in favor of enhanced binascii jpayne@68: # routines that accepted a max_line_length parameter. jpayne@68: def _encode_base64(data, max_line_length): jpayne@68: encoded_lines = [] jpayne@68: unencoded_bytes_per_line = max_line_length // 4 * 3 jpayne@68: for i in range(0, len(data), unencoded_bytes_per_line): jpayne@68: thisline = data[i:i+unencoded_bytes_per_line] jpayne@68: encoded_lines.append(binascii.b2a_base64(thisline).decode('ascii')) jpayne@68: return ''.join(encoded_lines) jpayne@68: jpayne@68: jpayne@68: def _encode_text(string, charset, cte, policy): jpayne@68: lines = string.encode(charset).splitlines() jpayne@68: linesep = policy.linesep.encode('ascii') jpayne@68: def embedded_body(lines): return linesep.join(lines) + linesep jpayne@68: def normal_body(lines): return b'\n'.join(lines) + b'\n' jpayne@68: if cte==None: jpayne@68: # Use heuristics to decide on the "best" encoding. jpayne@68: try: jpayne@68: return '7bit', normal_body(lines).decode('ascii') jpayne@68: except UnicodeDecodeError: jpayne@68: pass jpayne@68: if (policy.cte_type == '8bit' and jpayne@68: max(len(x) for x in lines) <= policy.max_line_length): jpayne@68: return '8bit', normal_body(lines).decode('ascii', 'surrogateescape') jpayne@68: sniff = embedded_body(lines[:10]) jpayne@68: sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'), jpayne@68: policy.max_line_length) jpayne@68: sniff_base64 = binascii.b2a_base64(sniff) jpayne@68: # This is a little unfair to qp; it includes lineseps, base64 doesn't. jpayne@68: if len(sniff_qp) > len(sniff_base64): jpayne@68: cte = 'base64' jpayne@68: else: jpayne@68: cte = 'quoted-printable' jpayne@68: if len(lines) <= 10: jpayne@68: return cte, sniff_qp jpayne@68: if cte == '7bit': jpayne@68: data = normal_body(lines).decode('ascii') jpayne@68: elif cte == '8bit': jpayne@68: data = normal_body(lines).decode('ascii', 'surrogateescape') jpayne@68: elif cte == 'quoted-printable': jpayne@68: data = quoprimime.body_encode(normal_body(lines).decode('latin-1'), jpayne@68: policy.max_line_length) jpayne@68: elif cte == 'base64': jpayne@68: data = _encode_base64(embedded_body(lines), policy.max_line_length) jpayne@68: else: jpayne@68: raise ValueError("Unknown content transfer encoding {}".format(cte)) jpayne@68: return cte, data jpayne@68: jpayne@68: jpayne@68: def set_text_content(msg, string, subtype="plain", charset='utf-8', cte=None, jpayne@68: disposition=None, filename=None, cid=None, jpayne@68: params=None, headers=None): jpayne@68: _prepare_set(msg, 'text', subtype, headers) jpayne@68: cte, payload = _encode_text(string, charset, cte, msg.policy) jpayne@68: msg.set_payload(payload) jpayne@68: msg.set_param('charset', jpayne@68: email.charset.ALIASES.get(charset, charset), jpayne@68: replace=True) jpayne@68: msg['Content-Transfer-Encoding'] = cte jpayne@68: _finalize_set(msg, disposition, filename, cid, params) jpayne@68: raw_data_manager.add_set_handler(str, set_text_content) jpayne@68: jpayne@68: jpayne@68: def set_message_content(msg, message, subtype="rfc822", cte=None, jpayne@68: disposition=None, filename=None, cid=None, jpayne@68: params=None, headers=None): jpayne@68: if subtype == 'partial': jpayne@68: raise ValueError("message/partial is not supported for Message objects") jpayne@68: if subtype == 'rfc822': jpayne@68: if cte not in (None, '7bit', '8bit', 'binary'): jpayne@68: # http://tools.ietf.org/html/rfc2046#section-5.2.1 mandate. jpayne@68: raise ValueError( jpayne@68: "message/rfc822 parts do not support cte={}".format(cte)) jpayne@68: # 8bit will get coerced on serialization if policy.cte_type='7bit'. We jpayne@68: # may end up claiming 8bit when it isn't needed, but the only negative jpayne@68: # result of that should be a gateway that needs to coerce to 7bit jpayne@68: # having to look through the whole embedded message to discover whether jpayne@68: # or not it actually has to do anything. jpayne@68: cte = '8bit' if cte is None else cte jpayne@68: elif subtype == 'external-body': jpayne@68: if cte not in (None, '7bit'): jpayne@68: # http://tools.ietf.org/html/rfc2046#section-5.2.3 mandate. jpayne@68: raise ValueError( jpayne@68: "message/external-body parts do not support cte={}".format(cte)) jpayne@68: cte = '7bit' jpayne@68: elif cte is None: jpayne@68: # http://tools.ietf.org/html/rfc2046#section-5.2.4 says all future jpayne@68: # subtypes should be restricted to 7bit, so assume that. jpayne@68: cte = '7bit' jpayne@68: _prepare_set(msg, 'message', subtype, headers) jpayne@68: msg.set_payload([message]) jpayne@68: msg['Content-Transfer-Encoding'] = cte jpayne@68: _finalize_set(msg, disposition, filename, cid, params) jpayne@68: raw_data_manager.add_set_handler(email.message.Message, set_message_content) jpayne@68: jpayne@68: jpayne@68: def set_bytes_content(msg, data, maintype, subtype, cte='base64', jpayne@68: disposition=None, filename=None, cid=None, jpayne@68: params=None, headers=None): jpayne@68: _prepare_set(msg, maintype, subtype, headers) jpayne@68: if cte == 'base64': jpayne@68: data = _encode_base64(data, max_line_length=msg.policy.max_line_length) jpayne@68: elif cte == 'quoted-printable': jpayne@68: # XXX: quoprimime.body_encode won't encode newline characters in data, jpayne@68: # so we can't use it. This means max_line_length is ignored. Another jpayne@68: # bug to fix later. (Note: encoders.quopri is broken on line ends.) jpayne@68: data = binascii.b2a_qp(data, istext=False, header=False, quotetabs=True) jpayne@68: data = data.decode('ascii') jpayne@68: elif cte == '7bit': jpayne@68: # Make sure it really is only ASCII. The early warning here seems jpayne@68: # worth the overhead...if you care write your own content manager :). jpayne@68: data.encode('ascii') jpayne@68: elif cte in ('8bit', 'binary'): jpayne@68: data = data.decode('ascii', 'surrogateescape') jpayne@68: msg.set_payload(data) jpayne@68: msg['Content-Transfer-Encoding'] = cte jpayne@68: _finalize_set(msg, disposition, filename, cid, params) jpayne@68: for typ in (bytes, bytearray, memoryview): jpayne@68: raw_data_manager.add_set_handler(typ, set_bytes_content)