Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3..../email
File: contentmanager.py
import binascii
[0] Fix | Delete
import email.charset
[1] Fix | Delete
import email.message
[2] Fix | Delete
import email.errors
[3] Fix | Delete
from email import quoprimime
[4] Fix | Delete
[5] Fix | Delete
class ContentManager:
[6] Fix | Delete
[7] Fix | Delete
def __init__(self):
[8] Fix | Delete
self.get_handlers = {}
[9] Fix | Delete
self.set_handlers = {}
[10] Fix | Delete
[11] Fix | Delete
def add_get_handler(self, key, handler):
[12] Fix | Delete
self.get_handlers[key] = handler
[13] Fix | Delete
[14] Fix | Delete
def get_content(self, msg, *args, **kw):
[15] Fix | Delete
content_type = msg.get_content_type()
[16] Fix | Delete
if content_type in self.get_handlers:
[17] Fix | Delete
return self.get_handlers[content_type](msg, *args, **kw)
[18] Fix | Delete
maintype = msg.get_content_maintype()
[19] Fix | Delete
if maintype in self.get_handlers:
[20] Fix | Delete
return self.get_handlers[maintype](msg, *args, **kw)
[21] Fix | Delete
if '' in self.get_handlers:
[22] Fix | Delete
return self.get_handlers[''](msg, *args, **kw)
[23] Fix | Delete
raise KeyError(content_type)
[24] Fix | Delete
[25] Fix | Delete
def add_set_handler(self, typekey, handler):
[26] Fix | Delete
self.set_handlers[typekey] = handler
[27] Fix | Delete
[28] Fix | Delete
def set_content(self, msg, obj, *args, **kw):
[29] Fix | Delete
if msg.get_content_maintype() == 'multipart':
[30] Fix | Delete
# XXX: is this error a good idea or not? We can remove it later,
[31] Fix | Delete
# but we can't add it later, so do it for now.
[32] Fix | Delete
raise TypeError("set_content not valid on multipart")
[33] Fix | Delete
handler = self._find_set_handler(msg, obj)
[34] Fix | Delete
msg.clear_content()
[35] Fix | Delete
handler(msg, obj, *args, **kw)
[36] Fix | Delete
[37] Fix | Delete
def _find_set_handler(self, msg, obj):
[38] Fix | Delete
full_path_for_error = None
[39] Fix | Delete
for typ in type(obj).__mro__:
[40] Fix | Delete
if typ in self.set_handlers:
[41] Fix | Delete
return self.set_handlers[typ]
[42] Fix | Delete
qname = typ.__qualname__
[43] Fix | Delete
modname = getattr(typ, '__module__', '')
[44] Fix | Delete
full_path = '.'.join((modname, qname)) if modname else qname
[45] Fix | Delete
if full_path_for_error is None:
[46] Fix | Delete
full_path_for_error = full_path
[47] Fix | Delete
if full_path in self.set_handlers:
[48] Fix | Delete
return self.set_handlers[full_path]
[49] Fix | Delete
if qname in self.set_handlers:
[50] Fix | Delete
return self.set_handlers[qname]
[51] Fix | Delete
name = typ.__name__
[52] Fix | Delete
if name in self.set_handlers:
[53] Fix | Delete
return self.set_handlers[name]
[54] Fix | Delete
if None in self.set_handlers:
[55] Fix | Delete
return self.set_handlers[None]
[56] Fix | Delete
raise KeyError(full_path_for_error)
[57] Fix | Delete
[58] Fix | Delete
[59] Fix | Delete
raw_data_manager = ContentManager()
[60] Fix | Delete
[61] Fix | Delete
[62] Fix | Delete
def get_text_content(msg, errors='replace'):
[63] Fix | Delete
content = msg.get_payload(decode=True)
[64] Fix | Delete
charset = msg.get_param('charset', 'ASCII')
[65] Fix | Delete
return content.decode(charset, errors=errors)
[66] Fix | Delete
raw_data_manager.add_get_handler('text', get_text_content)
[67] Fix | Delete
[68] Fix | Delete
[69] Fix | Delete
def get_non_text_content(msg):
[70] Fix | Delete
return msg.get_payload(decode=True)
[71] Fix | Delete
for maintype in 'audio image video application'.split():
[72] Fix | Delete
raw_data_manager.add_get_handler(maintype, get_non_text_content)
[73] Fix | Delete
[74] Fix | Delete
[75] Fix | Delete
def get_message_content(msg):
[76] Fix | Delete
return msg.get_payload(0)
[77] Fix | Delete
for subtype in 'rfc822 external-body'.split():
[78] Fix | Delete
raw_data_manager.add_get_handler('message/'+subtype, get_message_content)
[79] Fix | Delete
[80] Fix | Delete
[81] Fix | Delete
def get_and_fixup_unknown_message_content(msg):
[82] Fix | Delete
# If we don't understand a message subtype, we are supposed to treat it as
[83] Fix | Delete
# if it were application/octet-stream, per
[84] Fix | Delete
# tools.ietf.org/html/rfc2046#section-5.2.4. Feedparser doesn't do that,
[85] Fix | Delete
# so do our best to fix things up. Note that it is *not* appropriate to
[86] Fix | Delete
# model message/partial content as Message objects, so they are handled
[87] Fix | Delete
# here as well. (How to reassemble them is out of scope for this comment :)
[88] Fix | Delete
return bytes(msg.get_payload(0))
[89] Fix | Delete
raw_data_manager.add_get_handler('message',
[90] Fix | Delete
get_and_fixup_unknown_message_content)
[91] Fix | Delete
[92] Fix | Delete
[93] Fix | Delete
def _prepare_set(msg, maintype, subtype, headers):
[94] Fix | Delete
msg['Content-Type'] = '/'.join((maintype, subtype))
[95] Fix | Delete
if headers:
[96] Fix | Delete
if not hasattr(headers[0], 'name'):
[97] Fix | Delete
mp = msg.policy
[98] Fix | Delete
headers = [mp.header_factory(*mp.header_source_parse([header]))
[99] Fix | Delete
for header in headers]
[100] Fix | Delete
try:
[101] Fix | Delete
for header in headers:
[102] Fix | Delete
if header.defects:
[103] Fix | Delete
raise header.defects[0]
[104] Fix | Delete
msg[header.name] = header
[105] Fix | Delete
except email.errors.HeaderDefect as exc:
[106] Fix | Delete
raise ValueError("Invalid header: {}".format(
[107] Fix | Delete
header.fold(policy=msg.policy))) from exc
[108] Fix | Delete
[109] Fix | Delete
[110] Fix | Delete
def _finalize_set(msg, disposition, filename, cid, params):
[111] Fix | Delete
if disposition is None and filename is not None:
[112] Fix | Delete
disposition = 'attachment'
[113] Fix | Delete
if disposition is not None:
[114] Fix | Delete
msg['Content-Disposition'] = disposition
[115] Fix | Delete
if filename is not None:
[116] Fix | Delete
msg.set_param('filename',
[117] Fix | Delete
filename,
[118] Fix | Delete
header='Content-Disposition',
[119] Fix | Delete
replace=True)
[120] Fix | Delete
if cid is not None:
[121] Fix | Delete
msg['Content-ID'] = cid
[122] Fix | Delete
if params is not None:
[123] Fix | Delete
for key, value in params.items():
[124] Fix | Delete
msg.set_param(key, value)
[125] Fix | Delete
[126] Fix | Delete
[127] Fix | Delete
# XXX: This is a cleaned-up version of base64mime.body_encode (including a bug
[128] Fix | Delete
# fix in the calculation of unencoded_bytes_per_line). It would be nice to
[129] Fix | Delete
# drop both this and quoprimime.body_encode in favor of enhanced binascii
[130] Fix | Delete
# routines that accepted a max_line_length parameter.
[131] Fix | Delete
def _encode_base64(data, max_line_length):
[132] Fix | Delete
encoded_lines = []
[133] Fix | Delete
unencoded_bytes_per_line = max_line_length // 4 * 3
[134] Fix | Delete
for i in range(0, len(data), unencoded_bytes_per_line):
[135] Fix | Delete
thisline = data[i:i+unencoded_bytes_per_line]
[136] Fix | Delete
encoded_lines.append(binascii.b2a_base64(thisline).decode('ascii'))
[137] Fix | Delete
return ''.join(encoded_lines)
[138] Fix | Delete
[139] Fix | Delete
[140] Fix | Delete
def _encode_text(string, charset, cte, policy):
[141] Fix | Delete
lines = string.encode(charset).splitlines()
[142] Fix | Delete
linesep = policy.linesep.encode('ascii')
[143] Fix | Delete
def embedded_body(lines): return linesep.join(lines) + linesep
[144] Fix | Delete
def normal_body(lines): return b'\n'.join(lines) + b'\n'
[145] Fix | Delete
if cte==None:
[146] Fix | Delete
# Use heuristics to decide on the "best" encoding.
[147] Fix | Delete
try:
[148] Fix | Delete
return '7bit', normal_body(lines).decode('ascii')
[149] Fix | Delete
except UnicodeDecodeError:
[150] Fix | Delete
pass
[151] Fix | Delete
if (policy.cte_type == '8bit' and
[152] Fix | Delete
max(len(x) for x in lines) <= policy.max_line_length):
[153] Fix | Delete
return '8bit', normal_body(lines).decode('ascii', 'surrogateescape')
[154] Fix | Delete
sniff = embedded_body(lines[:10])
[155] Fix | Delete
sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'),
[156] Fix | Delete
policy.max_line_length)
[157] Fix | Delete
sniff_base64 = binascii.b2a_base64(sniff)
[158] Fix | Delete
# This is a little unfair to qp; it includes lineseps, base64 doesn't.
[159] Fix | Delete
if len(sniff_qp) > len(sniff_base64):
[160] Fix | Delete
cte = 'base64'
[161] Fix | Delete
else:
[162] Fix | Delete
cte = 'quoted-printable'
[163] Fix | Delete
if len(lines) <= 10:
[164] Fix | Delete
return cte, sniff_qp
[165] Fix | Delete
if cte == '7bit':
[166] Fix | Delete
data = normal_body(lines).decode('ascii')
[167] Fix | Delete
elif cte == '8bit':
[168] Fix | Delete
data = normal_body(lines).decode('ascii', 'surrogateescape')
[169] Fix | Delete
elif cte == 'quoted-printable':
[170] Fix | Delete
data = quoprimime.body_encode(normal_body(lines).decode('latin-1'),
[171] Fix | Delete
policy.max_line_length)
[172] Fix | Delete
elif cte == 'base64':
[173] Fix | Delete
data = _encode_base64(embedded_body(lines), policy.max_line_length)
[174] Fix | Delete
else:
[175] Fix | Delete
raise ValueError("Unknown content transfer encoding {}".format(cte))
[176] Fix | Delete
return cte, data
[177] Fix | Delete
[178] Fix | Delete
[179] Fix | Delete
def set_text_content(msg, string, subtype="plain", charset='utf-8', cte=None,
[180] Fix | Delete
disposition=None, filename=None, cid=None,
[181] Fix | Delete
params=None, headers=None):
[182] Fix | Delete
_prepare_set(msg, 'text', subtype, headers)
[183] Fix | Delete
cte, payload = _encode_text(string, charset, cte, msg.policy)
[184] Fix | Delete
msg.set_payload(payload)
[185] Fix | Delete
msg.set_param('charset',
[186] Fix | Delete
email.charset.ALIASES.get(charset, charset),
[187] Fix | Delete
replace=True)
[188] Fix | Delete
msg['Content-Transfer-Encoding'] = cte
[189] Fix | Delete
_finalize_set(msg, disposition, filename, cid, params)
[190] Fix | Delete
raw_data_manager.add_set_handler(str, set_text_content)
[191] Fix | Delete
[192] Fix | Delete
[193] Fix | Delete
def set_message_content(msg, message, subtype="rfc822", cte=None,
[194] Fix | Delete
disposition=None, filename=None, cid=None,
[195] Fix | Delete
params=None, headers=None):
[196] Fix | Delete
if subtype == 'partial':
[197] Fix | Delete
raise ValueError("message/partial is not supported for Message objects")
[198] Fix | Delete
if subtype == 'rfc822':
[199] Fix | Delete
if cte not in (None, '7bit', '8bit', 'binary'):
[200] Fix | Delete
# http://tools.ietf.org/html/rfc2046#section-5.2.1 mandate.
[201] Fix | Delete
raise ValueError(
[202] Fix | Delete
"message/rfc822 parts do not support cte={}".format(cte))
[203] Fix | Delete
# 8bit will get coerced on serialization if policy.cte_type='7bit'. We
[204] Fix | Delete
# may end up claiming 8bit when it isn't needed, but the only negative
[205] Fix | Delete
# result of that should be a gateway that needs to coerce to 7bit
[206] Fix | Delete
# having to look through the whole embedded message to discover whether
[207] Fix | Delete
# or not it actually has to do anything.
[208] Fix | Delete
cte = '8bit' if cte is None else cte
[209] Fix | Delete
elif subtype == 'external-body':
[210] Fix | Delete
if cte not in (None, '7bit'):
[211] Fix | Delete
# http://tools.ietf.org/html/rfc2046#section-5.2.3 mandate.
[212] Fix | Delete
raise ValueError(
[213] Fix | Delete
"message/external-body parts do not support cte={}".format(cte))
[214] Fix | Delete
cte = '7bit'
[215] Fix | Delete
elif cte is None:
[216] Fix | Delete
# http://tools.ietf.org/html/rfc2046#section-5.2.4 says all future
[217] Fix | Delete
# subtypes should be restricted to 7bit, so assume that.
[218] Fix | Delete
cte = '7bit'
[219] Fix | Delete
_prepare_set(msg, 'message', subtype, headers)
[220] Fix | Delete
msg.set_payload([message])
[221] Fix | Delete
msg['Content-Transfer-Encoding'] = cte
[222] Fix | Delete
_finalize_set(msg, disposition, filename, cid, params)
[223] Fix | Delete
raw_data_manager.add_set_handler(email.message.Message, set_message_content)
[224] Fix | Delete
[225] Fix | Delete
[226] Fix | Delete
def set_bytes_content(msg, data, maintype, subtype, cte='base64',
[227] Fix | Delete
disposition=None, filename=None, cid=None,
[228] Fix | Delete
params=None, headers=None):
[229] Fix | Delete
_prepare_set(msg, maintype, subtype, headers)
[230] Fix | Delete
if cte == 'base64':
[231] Fix | Delete
data = _encode_base64(data, max_line_length=msg.policy.max_line_length)
[232] Fix | Delete
elif cte == 'quoted-printable':
[233] Fix | Delete
# XXX: quoprimime.body_encode won't encode newline characters in data,
[234] Fix | Delete
# so we can't use it. This means max_line_length is ignored. Another
[235] Fix | Delete
# bug to fix later. (Note: encoders.quopri is broken on line ends.)
[236] Fix | Delete
data = binascii.b2a_qp(data, istext=False, header=False, quotetabs=True)
[237] Fix | Delete
data = data.decode('ascii')
[238] Fix | Delete
elif cte == '7bit':
[239] Fix | Delete
# Make sure it really is only ASCII. The early warning here seems
[240] Fix | Delete
# worth the overhead...if you care write your own content manager :).
[241] Fix | Delete
data.encode('ascii')
[242] Fix | Delete
elif cte in ('8bit', 'binary'):
[243] Fix | Delete
data = data.decode('ascii', 'surrogateescape')
[244] Fix | Delete
msg.set_payload(data)
[245] Fix | Delete
msg['Content-Transfer-Encoding'] = cte
[246] Fix | Delete
_finalize_set(msg, disposition, filename, cid, params)
[247] Fix | Delete
for typ in (bytes, bytearray, memoryview):
[248] Fix | Delete
raw_data_manager.add_set_handler(typ, set_bytes_content)
[249] Fix | Delete
[250] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function