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