jpayne@68
|
1 """Representing and manipulating email headers via custom objects.
|
jpayne@68
|
2
|
jpayne@68
|
3 This module provides an implementation of the HeaderRegistry API.
|
jpayne@68
|
4 The implementation is designed to flexibly follow RFC5322 rules.
|
jpayne@68
|
5
|
jpayne@68
|
6 Eventually HeaderRegistry will be a public API, but it isn't yet,
|
jpayne@68
|
7 and will probably change some before that happens.
|
jpayne@68
|
8
|
jpayne@68
|
9 """
|
jpayne@68
|
10 from types import MappingProxyType
|
jpayne@68
|
11
|
jpayne@68
|
12 from email import utils
|
jpayne@68
|
13 from email import errors
|
jpayne@68
|
14 from email import _header_value_parser as parser
|
jpayne@68
|
15
|
jpayne@68
|
16 class Address:
|
jpayne@68
|
17
|
jpayne@68
|
18 def __init__(self, display_name='', username='', domain='', addr_spec=None):
|
jpayne@68
|
19 """Create an object representing a full email address.
|
jpayne@68
|
20
|
jpayne@68
|
21 An address can have a 'display_name', a 'username', and a 'domain'. In
|
jpayne@68
|
22 addition to specifying the username and domain separately, they may be
|
jpayne@68
|
23 specified together by using the addr_spec keyword *instead of* the
|
jpayne@68
|
24 username and domain keywords. If an addr_spec string is specified it
|
jpayne@68
|
25 must be properly quoted according to RFC 5322 rules; an error will be
|
jpayne@68
|
26 raised if it is not.
|
jpayne@68
|
27
|
jpayne@68
|
28 An Address object has display_name, username, domain, and addr_spec
|
jpayne@68
|
29 attributes, all of which are read-only. The addr_spec and the string
|
jpayne@68
|
30 value of the object are both quoted according to RFC5322 rules, but
|
jpayne@68
|
31 without any Content Transfer Encoding.
|
jpayne@68
|
32
|
jpayne@68
|
33 """
|
jpayne@68
|
34 # This clause with its potential 'raise' may only happen when an
|
jpayne@68
|
35 # application program creates an Address object using an addr_spec
|
jpayne@68
|
36 # keyword. The email library code itself must always supply username
|
jpayne@68
|
37 # and domain.
|
jpayne@68
|
38 if addr_spec is not None:
|
jpayne@68
|
39 if username or domain:
|
jpayne@68
|
40 raise TypeError("addrspec specified when username and/or "
|
jpayne@68
|
41 "domain also specified")
|
jpayne@68
|
42 a_s, rest = parser.get_addr_spec(addr_spec)
|
jpayne@68
|
43 if rest:
|
jpayne@68
|
44 raise ValueError("Invalid addr_spec; only '{}' "
|
jpayne@68
|
45 "could be parsed from '{}'".format(
|
jpayne@68
|
46 a_s, addr_spec))
|
jpayne@68
|
47 if a_s.all_defects:
|
jpayne@68
|
48 raise a_s.all_defects[0]
|
jpayne@68
|
49 username = a_s.local_part
|
jpayne@68
|
50 domain = a_s.domain
|
jpayne@68
|
51 self._display_name = display_name
|
jpayne@68
|
52 self._username = username
|
jpayne@68
|
53 self._domain = domain
|
jpayne@68
|
54
|
jpayne@68
|
55 @property
|
jpayne@68
|
56 def display_name(self):
|
jpayne@68
|
57 return self._display_name
|
jpayne@68
|
58
|
jpayne@68
|
59 @property
|
jpayne@68
|
60 def username(self):
|
jpayne@68
|
61 return self._username
|
jpayne@68
|
62
|
jpayne@68
|
63 @property
|
jpayne@68
|
64 def domain(self):
|
jpayne@68
|
65 return self._domain
|
jpayne@68
|
66
|
jpayne@68
|
67 @property
|
jpayne@68
|
68 def addr_spec(self):
|
jpayne@68
|
69 """The addr_spec (username@domain) portion of the address, quoted
|
jpayne@68
|
70 according to RFC 5322 rules, but with no Content Transfer Encoding.
|
jpayne@68
|
71 """
|
jpayne@68
|
72 nameset = set(self.username)
|
jpayne@68
|
73 if len(nameset) > len(nameset-parser.DOT_ATOM_ENDS):
|
jpayne@68
|
74 lp = parser.quote_string(self.username)
|
jpayne@68
|
75 else:
|
jpayne@68
|
76 lp = self.username
|
jpayne@68
|
77 if self.domain:
|
jpayne@68
|
78 return lp + '@' + self.domain
|
jpayne@68
|
79 if not lp:
|
jpayne@68
|
80 return '<>'
|
jpayne@68
|
81 return lp
|
jpayne@68
|
82
|
jpayne@68
|
83 def __repr__(self):
|
jpayne@68
|
84 return "{}(display_name={!r}, username={!r}, domain={!r})".format(
|
jpayne@68
|
85 self.__class__.__name__,
|
jpayne@68
|
86 self.display_name, self.username, self.domain)
|
jpayne@68
|
87
|
jpayne@68
|
88 def __str__(self):
|
jpayne@68
|
89 nameset = set(self.display_name)
|
jpayne@68
|
90 if len(nameset) > len(nameset-parser.SPECIALS):
|
jpayne@68
|
91 disp = parser.quote_string(self.display_name)
|
jpayne@68
|
92 else:
|
jpayne@68
|
93 disp = self.display_name
|
jpayne@68
|
94 if disp:
|
jpayne@68
|
95 addr_spec = '' if self.addr_spec=='<>' else self.addr_spec
|
jpayne@68
|
96 return "{} <{}>".format(disp, addr_spec)
|
jpayne@68
|
97 return self.addr_spec
|
jpayne@68
|
98
|
jpayne@68
|
99 def __eq__(self, other):
|
jpayne@68
|
100 if type(other) != type(self):
|
jpayne@68
|
101 return False
|
jpayne@68
|
102 return (self.display_name == other.display_name and
|
jpayne@68
|
103 self.username == other.username and
|
jpayne@68
|
104 self.domain == other.domain)
|
jpayne@68
|
105
|
jpayne@68
|
106
|
jpayne@68
|
107 class Group:
|
jpayne@68
|
108
|
jpayne@68
|
109 def __init__(self, display_name=None, addresses=None):
|
jpayne@68
|
110 """Create an object representing an address group.
|
jpayne@68
|
111
|
jpayne@68
|
112 An address group consists of a display_name followed by colon and a
|
jpayne@68
|
113 list of addresses (see Address) terminated by a semi-colon. The Group
|
jpayne@68
|
114 is created by specifying a display_name and a possibly empty list of
|
jpayne@68
|
115 Address objects. A Group can also be used to represent a single
|
jpayne@68
|
116 address that is not in a group, which is convenient when manipulating
|
jpayne@68
|
117 lists that are a combination of Groups and individual Addresses. In
|
jpayne@68
|
118 this case the display_name should be set to None. In particular, the
|
jpayne@68
|
119 string representation of a Group whose display_name is None is the same
|
jpayne@68
|
120 as the Address object, if there is one and only one Address object in
|
jpayne@68
|
121 the addresses list.
|
jpayne@68
|
122
|
jpayne@68
|
123 """
|
jpayne@68
|
124 self._display_name = display_name
|
jpayne@68
|
125 self._addresses = tuple(addresses) if addresses else tuple()
|
jpayne@68
|
126
|
jpayne@68
|
127 @property
|
jpayne@68
|
128 def display_name(self):
|
jpayne@68
|
129 return self._display_name
|
jpayne@68
|
130
|
jpayne@68
|
131 @property
|
jpayne@68
|
132 def addresses(self):
|
jpayne@68
|
133 return self._addresses
|
jpayne@68
|
134
|
jpayne@68
|
135 def __repr__(self):
|
jpayne@68
|
136 return "{}(display_name={!r}, addresses={!r}".format(
|
jpayne@68
|
137 self.__class__.__name__,
|
jpayne@68
|
138 self.display_name, self.addresses)
|
jpayne@68
|
139
|
jpayne@68
|
140 def __str__(self):
|
jpayne@68
|
141 if self.display_name is None and len(self.addresses)==1:
|
jpayne@68
|
142 return str(self.addresses[0])
|
jpayne@68
|
143 disp = self.display_name
|
jpayne@68
|
144 if disp is not None:
|
jpayne@68
|
145 nameset = set(disp)
|
jpayne@68
|
146 if len(nameset) > len(nameset-parser.SPECIALS):
|
jpayne@68
|
147 disp = parser.quote_string(disp)
|
jpayne@68
|
148 adrstr = ", ".join(str(x) for x in self.addresses)
|
jpayne@68
|
149 adrstr = ' ' + adrstr if adrstr else adrstr
|
jpayne@68
|
150 return "{}:{};".format(disp, adrstr)
|
jpayne@68
|
151
|
jpayne@68
|
152 def __eq__(self, other):
|
jpayne@68
|
153 if type(other) != type(self):
|
jpayne@68
|
154 return False
|
jpayne@68
|
155 return (self.display_name == other.display_name and
|
jpayne@68
|
156 self.addresses == other.addresses)
|
jpayne@68
|
157
|
jpayne@68
|
158
|
jpayne@68
|
159 # Header Classes #
|
jpayne@68
|
160
|
jpayne@68
|
161 class BaseHeader(str):
|
jpayne@68
|
162
|
jpayne@68
|
163 """Base class for message headers.
|
jpayne@68
|
164
|
jpayne@68
|
165 Implements generic behavior and provides tools for subclasses.
|
jpayne@68
|
166
|
jpayne@68
|
167 A subclass must define a classmethod named 'parse' that takes an unfolded
|
jpayne@68
|
168 value string and a dictionary as its arguments. The dictionary will
|
jpayne@68
|
169 contain one key, 'defects', initialized to an empty list. After the call
|
jpayne@68
|
170 the dictionary must contain two additional keys: parse_tree, set to the
|
jpayne@68
|
171 parse tree obtained from parsing the header, and 'decoded', set to the
|
jpayne@68
|
172 string value of the idealized representation of the data from the value.
|
jpayne@68
|
173 (That is, encoded words are decoded, and values that have canonical
|
jpayne@68
|
174 representations are so represented.)
|
jpayne@68
|
175
|
jpayne@68
|
176 The defects key is intended to collect parsing defects, which the message
|
jpayne@68
|
177 parser will subsequently dispose of as appropriate. The parser should not,
|
jpayne@68
|
178 insofar as practical, raise any errors. Defects should be added to the
|
jpayne@68
|
179 list instead. The standard header parsers register defects for RFC
|
jpayne@68
|
180 compliance issues, for obsolete RFC syntax, and for unrecoverable parsing
|
jpayne@68
|
181 errors.
|
jpayne@68
|
182
|
jpayne@68
|
183 The parse method may add additional keys to the dictionary. In this case
|
jpayne@68
|
184 the subclass must define an 'init' method, which will be passed the
|
jpayne@68
|
185 dictionary as its keyword arguments. The method should use (usually by
|
jpayne@68
|
186 setting them as the value of similarly named attributes) and remove all the
|
jpayne@68
|
187 extra keys added by its parse method, and then use super to call its parent
|
jpayne@68
|
188 class with the remaining arguments and keywords.
|
jpayne@68
|
189
|
jpayne@68
|
190 The subclass should also make sure that a 'max_count' attribute is defined
|
jpayne@68
|
191 that is either None or 1. XXX: need to better define this API.
|
jpayne@68
|
192
|
jpayne@68
|
193 """
|
jpayne@68
|
194
|
jpayne@68
|
195 def __new__(cls, name, value):
|
jpayne@68
|
196 kwds = {'defects': []}
|
jpayne@68
|
197 cls.parse(value, kwds)
|
jpayne@68
|
198 if utils._has_surrogates(kwds['decoded']):
|
jpayne@68
|
199 kwds['decoded'] = utils._sanitize(kwds['decoded'])
|
jpayne@68
|
200 self = str.__new__(cls, kwds['decoded'])
|
jpayne@68
|
201 del kwds['decoded']
|
jpayne@68
|
202 self.init(name, **kwds)
|
jpayne@68
|
203 return self
|
jpayne@68
|
204
|
jpayne@68
|
205 def init(self, name, *, parse_tree, defects):
|
jpayne@68
|
206 self._name = name
|
jpayne@68
|
207 self._parse_tree = parse_tree
|
jpayne@68
|
208 self._defects = defects
|
jpayne@68
|
209
|
jpayne@68
|
210 @property
|
jpayne@68
|
211 def name(self):
|
jpayne@68
|
212 return self._name
|
jpayne@68
|
213
|
jpayne@68
|
214 @property
|
jpayne@68
|
215 def defects(self):
|
jpayne@68
|
216 return tuple(self._defects)
|
jpayne@68
|
217
|
jpayne@68
|
218 def __reduce__(self):
|
jpayne@68
|
219 return (
|
jpayne@68
|
220 _reconstruct_header,
|
jpayne@68
|
221 (
|
jpayne@68
|
222 self.__class__.__name__,
|
jpayne@68
|
223 self.__class__.__bases__,
|
jpayne@68
|
224 str(self),
|
jpayne@68
|
225 ),
|
jpayne@68
|
226 self.__dict__)
|
jpayne@68
|
227
|
jpayne@68
|
228 @classmethod
|
jpayne@68
|
229 def _reconstruct(cls, value):
|
jpayne@68
|
230 return str.__new__(cls, value)
|
jpayne@68
|
231
|
jpayne@68
|
232 def fold(self, *, policy):
|
jpayne@68
|
233 """Fold header according to policy.
|
jpayne@68
|
234
|
jpayne@68
|
235 The parsed representation of the header is folded according to
|
jpayne@68
|
236 RFC5322 rules, as modified by the policy. If the parse tree
|
jpayne@68
|
237 contains surrogateescaped bytes, the bytes are CTE encoded using
|
jpayne@68
|
238 the charset 'unknown-8bit".
|
jpayne@68
|
239
|
jpayne@68
|
240 Any non-ASCII characters in the parse tree are CTE encoded using
|
jpayne@68
|
241 charset utf-8. XXX: make this a policy setting.
|
jpayne@68
|
242
|
jpayne@68
|
243 The returned value is an ASCII-only string possibly containing linesep
|
jpayne@68
|
244 characters, and ending with a linesep character. The string includes
|
jpayne@68
|
245 the header name and the ': ' separator.
|
jpayne@68
|
246
|
jpayne@68
|
247 """
|
jpayne@68
|
248 # At some point we need to put fws here if it was in the source.
|
jpayne@68
|
249 header = parser.Header([
|
jpayne@68
|
250 parser.HeaderLabel([
|
jpayne@68
|
251 parser.ValueTerminal(self.name, 'header-name'),
|
jpayne@68
|
252 parser.ValueTerminal(':', 'header-sep')]),
|
jpayne@68
|
253 ])
|
jpayne@68
|
254 if self._parse_tree:
|
jpayne@68
|
255 header.append(
|
jpayne@68
|
256 parser.CFWSList([parser.WhiteSpaceTerminal(' ', 'fws')]))
|
jpayne@68
|
257 header.append(self._parse_tree)
|
jpayne@68
|
258 return header.fold(policy=policy)
|
jpayne@68
|
259
|
jpayne@68
|
260
|
jpayne@68
|
261 def _reconstruct_header(cls_name, bases, value):
|
jpayne@68
|
262 return type(cls_name, bases, {})._reconstruct(value)
|
jpayne@68
|
263
|
jpayne@68
|
264
|
jpayne@68
|
265 class UnstructuredHeader:
|
jpayne@68
|
266
|
jpayne@68
|
267 max_count = None
|
jpayne@68
|
268 value_parser = staticmethod(parser.get_unstructured)
|
jpayne@68
|
269
|
jpayne@68
|
270 @classmethod
|
jpayne@68
|
271 def parse(cls, value, kwds):
|
jpayne@68
|
272 kwds['parse_tree'] = cls.value_parser(value)
|
jpayne@68
|
273 kwds['decoded'] = str(kwds['parse_tree'])
|
jpayne@68
|
274
|
jpayne@68
|
275
|
jpayne@68
|
276 class UniqueUnstructuredHeader(UnstructuredHeader):
|
jpayne@68
|
277
|
jpayne@68
|
278 max_count = 1
|
jpayne@68
|
279
|
jpayne@68
|
280
|
jpayne@68
|
281 class DateHeader:
|
jpayne@68
|
282
|
jpayne@68
|
283 """Header whose value consists of a single timestamp.
|
jpayne@68
|
284
|
jpayne@68
|
285 Provides an additional attribute, datetime, which is either an aware
|
jpayne@68
|
286 datetime using a timezone, or a naive datetime if the timezone
|
jpayne@68
|
287 in the input string is -0000. Also accepts a datetime as input.
|
jpayne@68
|
288 The 'value' attribute is the normalized form of the timestamp,
|
jpayne@68
|
289 which means it is the output of format_datetime on the datetime.
|
jpayne@68
|
290 """
|
jpayne@68
|
291
|
jpayne@68
|
292 max_count = None
|
jpayne@68
|
293
|
jpayne@68
|
294 # This is used only for folding, not for creating 'decoded'.
|
jpayne@68
|
295 value_parser = staticmethod(parser.get_unstructured)
|
jpayne@68
|
296
|
jpayne@68
|
297 @classmethod
|
jpayne@68
|
298 def parse(cls, value, kwds):
|
jpayne@68
|
299 if not value:
|
jpayne@68
|
300 kwds['defects'].append(errors.HeaderMissingRequiredValue())
|
jpayne@68
|
301 kwds['datetime'] = None
|
jpayne@68
|
302 kwds['decoded'] = ''
|
jpayne@68
|
303 kwds['parse_tree'] = parser.TokenList()
|
jpayne@68
|
304 return
|
jpayne@68
|
305 if isinstance(value, str):
|
jpayne@68
|
306 value = utils.parsedate_to_datetime(value)
|
jpayne@68
|
307 kwds['datetime'] = value
|
jpayne@68
|
308 kwds['decoded'] = utils.format_datetime(kwds['datetime'])
|
jpayne@68
|
309 kwds['parse_tree'] = cls.value_parser(kwds['decoded'])
|
jpayne@68
|
310
|
jpayne@68
|
311 def init(self, *args, **kw):
|
jpayne@68
|
312 self._datetime = kw.pop('datetime')
|
jpayne@68
|
313 super().init(*args, **kw)
|
jpayne@68
|
314
|
jpayne@68
|
315 @property
|
jpayne@68
|
316 def datetime(self):
|
jpayne@68
|
317 return self._datetime
|
jpayne@68
|
318
|
jpayne@68
|
319
|
jpayne@68
|
320 class UniqueDateHeader(DateHeader):
|
jpayne@68
|
321
|
jpayne@68
|
322 max_count = 1
|
jpayne@68
|
323
|
jpayne@68
|
324
|
jpayne@68
|
325 class AddressHeader:
|
jpayne@68
|
326
|
jpayne@68
|
327 max_count = None
|
jpayne@68
|
328
|
jpayne@68
|
329 @staticmethod
|
jpayne@68
|
330 def value_parser(value):
|
jpayne@68
|
331 address_list, value = parser.get_address_list(value)
|
jpayne@68
|
332 assert not value, 'this should not happen'
|
jpayne@68
|
333 return address_list
|
jpayne@68
|
334
|
jpayne@68
|
335 @classmethod
|
jpayne@68
|
336 def parse(cls, value, kwds):
|
jpayne@68
|
337 if isinstance(value, str):
|
jpayne@68
|
338 # We are translating here from the RFC language (address/mailbox)
|
jpayne@68
|
339 # to our API language (group/address).
|
jpayne@68
|
340 kwds['parse_tree'] = address_list = cls.value_parser(value)
|
jpayne@68
|
341 groups = []
|
jpayne@68
|
342 for addr in address_list.addresses:
|
jpayne@68
|
343 groups.append(Group(addr.display_name,
|
jpayne@68
|
344 [Address(mb.display_name or '',
|
jpayne@68
|
345 mb.local_part or '',
|
jpayne@68
|
346 mb.domain or '')
|
jpayne@68
|
347 for mb in addr.all_mailboxes]))
|
jpayne@68
|
348 defects = list(address_list.all_defects)
|
jpayne@68
|
349 else:
|
jpayne@68
|
350 # Assume it is Address/Group stuff
|
jpayne@68
|
351 if not hasattr(value, '__iter__'):
|
jpayne@68
|
352 value = [value]
|
jpayne@68
|
353 groups = [Group(None, [item]) if not hasattr(item, 'addresses')
|
jpayne@68
|
354 else item
|
jpayne@68
|
355 for item in value]
|
jpayne@68
|
356 defects = []
|
jpayne@68
|
357 kwds['groups'] = groups
|
jpayne@68
|
358 kwds['defects'] = defects
|
jpayne@68
|
359 kwds['decoded'] = ', '.join([str(item) for item in groups])
|
jpayne@68
|
360 if 'parse_tree' not in kwds:
|
jpayne@68
|
361 kwds['parse_tree'] = cls.value_parser(kwds['decoded'])
|
jpayne@68
|
362
|
jpayne@68
|
363 def init(self, *args, **kw):
|
jpayne@68
|
364 self._groups = tuple(kw.pop('groups'))
|
jpayne@68
|
365 self._addresses = None
|
jpayne@68
|
366 super().init(*args, **kw)
|
jpayne@68
|
367
|
jpayne@68
|
368 @property
|
jpayne@68
|
369 def groups(self):
|
jpayne@68
|
370 return self._groups
|
jpayne@68
|
371
|
jpayne@68
|
372 @property
|
jpayne@68
|
373 def addresses(self):
|
jpayne@68
|
374 if self._addresses is None:
|
jpayne@68
|
375 self._addresses = tuple(address for group in self._groups
|
jpayne@68
|
376 for address in group.addresses)
|
jpayne@68
|
377 return self._addresses
|
jpayne@68
|
378
|
jpayne@68
|
379
|
jpayne@68
|
380 class UniqueAddressHeader(AddressHeader):
|
jpayne@68
|
381
|
jpayne@68
|
382 max_count = 1
|
jpayne@68
|
383
|
jpayne@68
|
384
|
jpayne@68
|
385 class SingleAddressHeader(AddressHeader):
|
jpayne@68
|
386
|
jpayne@68
|
387 @property
|
jpayne@68
|
388 def address(self):
|
jpayne@68
|
389 if len(self.addresses)!=1:
|
jpayne@68
|
390 raise ValueError(("value of single address header {} is not "
|
jpayne@68
|
391 "a single address").format(self.name))
|
jpayne@68
|
392 return self.addresses[0]
|
jpayne@68
|
393
|
jpayne@68
|
394
|
jpayne@68
|
395 class UniqueSingleAddressHeader(SingleAddressHeader):
|
jpayne@68
|
396
|
jpayne@68
|
397 max_count = 1
|
jpayne@68
|
398
|
jpayne@68
|
399
|
jpayne@68
|
400 class MIMEVersionHeader:
|
jpayne@68
|
401
|
jpayne@68
|
402 max_count = 1
|
jpayne@68
|
403
|
jpayne@68
|
404 value_parser = staticmethod(parser.parse_mime_version)
|
jpayne@68
|
405
|
jpayne@68
|
406 @classmethod
|
jpayne@68
|
407 def parse(cls, value, kwds):
|
jpayne@68
|
408 kwds['parse_tree'] = parse_tree = cls.value_parser(value)
|
jpayne@68
|
409 kwds['decoded'] = str(parse_tree)
|
jpayne@68
|
410 kwds['defects'].extend(parse_tree.all_defects)
|
jpayne@68
|
411 kwds['major'] = None if parse_tree.minor is None else parse_tree.major
|
jpayne@68
|
412 kwds['minor'] = parse_tree.minor
|
jpayne@68
|
413 if parse_tree.minor is not None:
|
jpayne@68
|
414 kwds['version'] = '{}.{}'.format(kwds['major'], kwds['minor'])
|
jpayne@68
|
415 else:
|
jpayne@68
|
416 kwds['version'] = None
|
jpayne@68
|
417
|
jpayne@68
|
418 def init(self, *args, **kw):
|
jpayne@68
|
419 self._version = kw.pop('version')
|
jpayne@68
|
420 self._major = kw.pop('major')
|
jpayne@68
|
421 self._minor = kw.pop('minor')
|
jpayne@68
|
422 super().init(*args, **kw)
|
jpayne@68
|
423
|
jpayne@68
|
424 @property
|
jpayne@68
|
425 def major(self):
|
jpayne@68
|
426 return self._major
|
jpayne@68
|
427
|
jpayne@68
|
428 @property
|
jpayne@68
|
429 def minor(self):
|
jpayne@68
|
430 return self._minor
|
jpayne@68
|
431
|
jpayne@68
|
432 @property
|
jpayne@68
|
433 def version(self):
|
jpayne@68
|
434 return self._version
|
jpayne@68
|
435
|
jpayne@68
|
436
|
jpayne@68
|
437 class ParameterizedMIMEHeader:
|
jpayne@68
|
438
|
jpayne@68
|
439 # Mixin that handles the params dict. Must be subclassed and
|
jpayne@68
|
440 # a property value_parser for the specific header provided.
|
jpayne@68
|
441
|
jpayne@68
|
442 max_count = 1
|
jpayne@68
|
443
|
jpayne@68
|
444 @classmethod
|
jpayne@68
|
445 def parse(cls, value, kwds):
|
jpayne@68
|
446 kwds['parse_tree'] = parse_tree = cls.value_parser(value)
|
jpayne@68
|
447 kwds['decoded'] = str(parse_tree)
|
jpayne@68
|
448 kwds['defects'].extend(parse_tree.all_defects)
|
jpayne@68
|
449 if parse_tree.params is None:
|
jpayne@68
|
450 kwds['params'] = {}
|
jpayne@68
|
451 else:
|
jpayne@68
|
452 # The MIME RFCs specify that parameter ordering is arbitrary.
|
jpayne@68
|
453 kwds['params'] = {utils._sanitize(name).lower():
|
jpayne@68
|
454 utils._sanitize(value)
|
jpayne@68
|
455 for name, value in parse_tree.params}
|
jpayne@68
|
456
|
jpayne@68
|
457 def init(self, *args, **kw):
|
jpayne@68
|
458 self._params = kw.pop('params')
|
jpayne@68
|
459 super().init(*args, **kw)
|
jpayne@68
|
460
|
jpayne@68
|
461 @property
|
jpayne@68
|
462 def params(self):
|
jpayne@68
|
463 return MappingProxyType(self._params)
|
jpayne@68
|
464
|
jpayne@68
|
465
|
jpayne@68
|
466 class ContentTypeHeader(ParameterizedMIMEHeader):
|
jpayne@68
|
467
|
jpayne@68
|
468 value_parser = staticmethod(parser.parse_content_type_header)
|
jpayne@68
|
469
|
jpayne@68
|
470 def init(self, *args, **kw):
|
jpayne@68
|
471 super().init(*args, **kw)
|
jpayne@68
|
472 self._maintype = utils._sanitize(self._parse_tree.maintype)
|
jpayne@68
|
473 self._subtype = utils._sanitize(self._parse_tree.subtype)
|
jpayne@68
|
474
|
jpayne@68
|
475 @property
|
jpayne@68
|
476 def maintype(self):
|
jpayne@68
|
477 return self._maintype
|
jpayne@68
|
478
|
jpayne@68
|
479 @property
|
jpayne@68
|
480 def subtype(self):
|
jpayne@68
|
481 return self._subtype
|
jpayne@68
|
482
|
jpayne@68
|
483 @property
|
jpayne@68
|
484 def content_type(self):
|
jpayne@68
|
485 return self.maintype + '/' + self.subtype
|
jpayne@68
|
486
|
jpayne@68
|
487
|
jpayne@68
|
488 class ContentDispositionHeader(ParameterizedMIMEHeader):
|
jpayne@68
|
489
|
jpayne@68
|
490 value_parser = staticmethod(parser.parse_content_disposition_header)
|
jpayne@68
|
491
|
jpayne@68
|
492 def init(self, *args, **kw):
|
jpayne@68
|
493 super().init(*args, **kw)
|
jpayne@68
|
494 cd = self._parse_tree.content_disposition
|
jpayne@68
|
495 self._content_disposition = cd if cd is None else utils._sanitize(cd)
|
jpayne@68
|
496
|
jpayne@68
|
497 @property
|
jpayne@68
|
498 def content_disposition(self):
|
jpayne@68
|
499 return self._content_disposition
|
jpayne@68
|
500
|
jpayne@68
|
501
|
jpayne@68
|
502 class ContentTransferEncodingHeader:
|
jpayne@68
|
503
|
jpayne@68
|
504 max_count = 1
|
jpayne@68
|
505
|
jpayne@68
|
506 value_parser = staticmethod(parser.parse_content_transfer_encoding_header)
|
jpayne@68
|
507
|
jpayne@68
|
508 @classmethod
|
jpayne@68
|
509 def parse(cls, value, kwds):
|
jpayne@68
|
510 kwds['parse_tree'] = parse_tree = cls.value_parser(value)
|
jpayne@68
|
511 kwds['decoded'] = str(parse_tree)
|
jpayne@68
|
512 kwds['defects'].extend(parse_tree.all_defects)
|
jpayne@68
|
513
|
jpayne@68
|
514 def init(self, *args, **kw):
|
jpayne@68
|
515 super().init(*args, **kw)
|
jpayne@68
|
516 self._cte = utils._sanitize(self._parse_tree.cte)
|
jpayne@68
|
517
|
jpayne@68
|
518 @property
|
jpayne@68
|
519 def cte(self):
|
jpayne@68
|
520 return self._cte
|
jpayne@68
|
521
|
jpayne@68
|
522
|
jpayne@68
|
523 class MessageIDHeader:
|
jpayne@68
|
524
|
jpayne@68
|
525 max_count = 1
|
jpayne@68
|
526 value_parser = staticmethod(parser.parse_message_id)
|
jpayne@68
|
527
|
jpayne@68
|
528 @classmethod
|
jpayne@68
|
529 def parse(cls, value, kwds):
|
jpayne@68
|
530 kwds['parse_tree'] = parse_tree = cls.value_parser(value)
|
jpayne@68
|
531 kwds['decoded'] = str(parse_tree)
|
jpayne@68
|
532 kwds['defects'].extend(parse_tree.all_defects)
|
jpayne@68
|
533
|
jpayne@68
|
534
|
jpayne@68
|
535 # The header factory #
|
jpayne@68
|
536
|
jpayne@68
|
537 _default_header_map = {
|
jpayne@68
|
538 'subject': UniqueUnstructuredHeader,
|
jpayne@68
|
539 'date': UniqueDateHeader,
|
jpayne@68
|
540 'resent-date': DateHeader,
|
jpayne@68
|
541 'orig-date': UniqueDateHeader,
|
jpayne@68
|
542 'sender': UniqueSingleAddressHeader,
|
jpayne@68
|
543 'resent-sender': SingleAddressHeader,
|
jpayne@68
|
544 'to': UniqueAddressHeader,
|
jpayne@68
|
545 'resent-to': AddressHeader,
|
jpayne@68
|
546 'cc': UniqueAddressHeader,
|
jpayne@68
|
547 'resent-cc': AddressHeader,
|
jpayne@68
|
548 'bcc': UniqueAddressHeader,
|
jpayne@68
|
549 'resent-bcc': AddressHeader,
|
jpayne@68
|
550 'from': UniqueAddressHeader,
|
jpayne@68
|
551 'resent-from': AddressHeader,
|
jpayne@68
|
552 'reply-to': UniqueAddressHeader,
|
jpayne@68
|
553 'mime-version': MIMEVersionHeader,
|
jpayne@68
|
554 'content-type': ContentTypeHeader,
|
jpayne@68
|
555 'content-disposition': ContentDispositionHeader,
|
jpayne@68
|
556 'content-transfer-encoding': ContentTransferEncodingHeader,
|
jpayne@68
|
557 'message-id': MessageIDHeader,
|
jpayne@68
|
558 }
|
jpayne@68
|
559
|
jpayne@68
|
560 class HeaderRegistry:
|
jpayne@68
|
561
|
jpayne@68
|
562 """A header_factory and header registry."""
|
jpayne@68
|
563
|
jpayne@68
|
564 def __init__(self, base_class=BaseHeader, default_class=UnstructuredHeader,
|
jpayne@68
|
565 use_default_map=True):
|
jpayne@68
|
566 """Create a header_factory that works with the Policy API.
|
jpayne@68
|
567
|
jpayne@68
|
568 base_class is the class that will be the last class in the created
|
jpayne@68
|
569 header class's __bases__ list. default_class is the class that will be
|
jpayne@68
|
570 used if "name" (see __call__) does not appear in the registry.
|
jpayne@68
|
571 use_default_map controls whether or not the default mapping of names to
|
jpayne@68
|
572 specialized classes is copied in to the registry when the factory is
|
jpayne@68
|
573 created. The default is True.
|
jpayne@68
|
574
|
jpayne@68
|
575 """
|
jpayne@68
|
576 self.registry = {}
|
jpayne@68
|
577 self.base_class = base_class
|
jpayne@68
|
578 self.default_class = default_class
|
jpayne@68
|
579 if use_default_map:
|
jpayne@68
|
580 self.registry.update(_default_header_map)
|
jpayne@68
|
581
|
jpayne@68
|
582 def map_to_type(self, name, cls):
|
jpayne@68
|
583 """Register cls as the specialized class for handling "name" headers.
|
jpayne@68
|
584
|
jpayne@68
|
585 """
|
jpayne@68
|
586 self.registry[name.lower()] = cls
|
jpayne@68
|
587
|
jpayne@68
|
588 def __getitem__(self, name):
|
jpayne@68
|
589 cls = self.registry.get(name.lower(), self.default_class)
|
jpayne@68
|
590 return type('_'+cls.__name__, (cls, self.base_class), {})
|
jpayne@68
|
591
|
jpayne@68
|
592 def __call__(self, name, value):
|
jpayne@68
|
593 """Create a header instance for header 'name' from 'value'.
|
jpayne@68
|
594
|
jpayne@68
|
595 Creates a header instance by creating a specialized class for parsing
|
jpayne@68
|
596 and representing the specified header by combining the factory
|
jpayne@68
|
597 base_class with a specialized class from the registry or the
|
jpayne@68
|
598 default_class, and passing the name and value to the constructed
|
jpayne@68
|
599 class's constructor.
|
jpayne@68
|
600
|
jpayne@68
|
601 """
|
jpayne@68
|
602 return self[name](name, value)
|