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