PageRenderTime 35ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/email/generator.py

https://bitbucket.org/pwaller/pypy
Python | 364 lines | 326 code | 11 blank | 27 comment | 5 complexity | 3a6c143eeca27909a3f901414e56302f MD5 | raw file
  1. # Copyright (C) 2001-2010 Python Software Foundation
  2. # Contact: email-sig@python.org
  3. """Classes to generate plain text from a message object tree."""
  4. __all__ = ['Generator', 'DecodedGenerator']
  5. import re
  6. import sys
  7. import time
  8. import random
  9. import warnings
  10. from cStringIO import StringIO
  11. from email.header import Header
  12. UNDERSCORE = '_'
  13. NL = '\n'
  14. fcre = re.compile(r'^From ', re.MULTILINE)
  15. def _is8bitstring(s):
  16. if isinstance(s, str):
  17. try:
  18. unicode(s, 'us-ascii')
  19. except UnicodeError:
  20. return True
  21. return False
  22. class Generator:
  23. """Generates output from a Message object tree.
  24. This basic generator writes the message to the given file object as plain
  25. text.
  26. """
  27. #
  28. # Public interface
  29. #
  30. def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
  31. """Create the generator for message flattening.
  32. outfp is the output file-like object for writing the message to. It
  33. must have a write() method.
  34. Optional mangle_from_ is a flag that, when True (the default), escapes
  35. From_ lines in the body of the message by putting a `>' in front of
  36. them.
  37. Optional maxheaderlen specifies the longest length for a non-continued
  38. header. When a header line is longer (in characters, with tabs
  39. expanded to 8 spaces) than maxheaderlen, the header will split as
  40. defined in the Header class. Set maxheaderlen to zero to disable
  41. header wrapping. The default is 78, as recommended (but not required)
  42. by RFC 2822.
  43. """
  44. self._fp = outfp
  45. self._mangle_from_ = mangle_from_
  46. self._maxheaderlen = maxheaderlen
  47. def write(self, s):
  48. # Just delegate to the file object
  49. self._fp.write(s)
  50. def flatten(self, msg, unixfrom=False):
  51. """Print the message object tree rooted at msg to the output file
  52. specified when the Generator instance was created.
  53. unixfrom is a flag that forces the printing of a Unix From_ delimiter
  54. before the first object in the message tree. If the original message
  55. has no From_ delimiter, a `standard' one is crafted. By default, this
  56. is False to inhibit the printing of any From_ delimiter.
  57. Note that for subobjects, no From_ line is printed.
  58. """
  59. if unixfrom:
  60. ufrom = msg.get_unixfrom()
  61. if not ufrom:
  62. ufrom = 'From nobody ' + time.ctime(time.time())
  63. print >> self._fp, ufrom
  64. self._write(msg)
  65. def clone(self, fp):
  66. """Clone this generator with the exact same options."""
  67. return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
  68. #
  69. # Protected interface - undocumented ;/
  70. #
  71. def _write(self, msg):
  72. # We can't write the headers yet because of the following scenario:
  73. # say a multipart message includes the boundary string somewhere in
  74. # its body. We'd have to calculate the new boundary /before/ we write
  75. # the headers so that we can write the correct Content-Type:
  76. # parameter.
  77. #
  78. # The way we do this, so as to make the _handle_*() methods simpler,
  79. # is to cache any subpart writes into a StringIO. The we write the
  80. # headers and the StringIO contents. That way, subpart handlers can
  81. # Do The Right Thing, and can still modify the Content-Type: header if
  82. # necessary.
  83. oldfp = self._fp
  84. try:
  85. self._fp = sfp = StringIO()
  86. self._dispatch(msg)
  87. finally:
  88. self._fp = oldfp
  89. # Write the headers. First we see if the message object wants to
  90. # handle that itself. If not, we'll do it generically.
  91. meth = getattr(msg, '_write_headers', None)
  92. if meth is None:
  93. self._write_headers(msg)
  94. else:
  95. meth(self)
  96. self._fp.write(sfp.getvalue())
  97. def _dispatch(self, msg):
  98. # Get the Content-Type: for the message, then try to dispatch to
  99. # self._handle_<maintype>_<subtype>(). If there's no handler for the
  100. # full MIME type, then dispatch to self._handle_<maintype>(). If
  101. # that's missing too, then dispatch to self._writeBody().
  102. main = msg.get_content_maintype()
  103. sub = msg.get_content_subtype()
  104. specific = UNDERSCORE.join((main, sub)).replace('-', '_')
  105. meth = getattr(self, '_handle_' + specific, None)
  106. if meth is None:
  107. generic = main.replace('-', '_')
  108. meth = getattr(self, '_handle_' + generic, None)
  109. if meth is None:
  110. meth = self._writeBody
  111. meth(msg)
  112. #
  113. # Default handlers
  114. #
  115. def _write_headers(self, msg):
  116. for h, v in msg.items():
  117. print >> self._fp, '%s:' % h,
  118. if self._maxheaderlen == 0:
  119. # Explicit no-wrapping
  120. print >> self._fp, v
  121. elif isinstance(v, Header):
  122. # Header instances know what to do
  123. print >> self._fp, v.encode()
  124. elif _is8bitstring(v):
  125. # If we have raw 8bit data in a byte string, we have no idea
  126. # what the encoding is. There is no safe way to split this
  127. # string. If it's ascii-subset, then we could do a normal
  128. # ascii split, but if it's multibyte then we could break the
  129. # string. There's no way to know so the least harm seems to
  130. # be to not split the string and risk it being too long.
  131. print >> self._fp, v
  132. else:
  133. # Header's got lots of smarts, so use it. Note that this is
  134. # fundamentally broken though because we lose idempotency when
  135. # the header string is continued with tabs. It will now be
  136. # continued with spaces. This was reversedly broken before we
  137. # fixed bug 1974. Either way, we lose.
  138. print >> self._fp, Header(
  139. v, maxlinelen=self._maxheaderlen, header_name=h).encode()
  140. # A blank line always separates headers from body
  141. print >> self._fp
  142. #
  143. # Handlers for writing types and subtypes
  144. #
  145. def _handle_text(self, msg):
  146. payload = msg.get_payload()
  147. if payload is None:
  148. return
  149. if not isinstance(payload, basestring):
  150. raise TypeError('string payload expected: %s' % type(payload))
  151. if self._mangle_from_:
  152. payload = fcre.sub('>From ', payload)
  153. self._fp.write(payload)
  154. # Default body handler
  155. _writeBody = _handle_text
  156. def _handle_multipart(self, msg):
  157. # The trick here is to write out each part separately, merge them all
  158. # together, and then make sure that the boundary we've chosen isn't
  159. # present in the payload.
  160. msgtexts = []
  161. subparts = msg.get_payload()
  162. if subparts is None:
  163. subparts = []
  164. elif isinstance(subparts, basestring):
  165. # e.g. a non-strict parse of a message with no starting boundary.
  166. self._fp.write(subparts)
  167. return
  168. elif not isinstance(subparts, list):
  169. # Scalar payload
  170. subparts = [subparts]
  171. for part in subparts:
  172. s = StringIO()
  173. g = self.clone(s)
  174. g.flatten(part, unixfrom=False)
  175. msgtexts.append(s.getvalue())
  176. # BAW: What about boundaries that are wrapped in double-quotes?
  177. boundary = msg.get_boundary()
  178. if not boundary:
  179. # Create a boundary that doesn't appear in any of the
  180. # message texts.
  181. alltext = NL.join(msgtexts)
  182. boundary = _make_boundary(alltext)
  183. msg.set_boundary(boundary)
  184. # If there's a preamble, write it out, with a trailing CRLF
  185. if msg.preamble is not None:
  186. print >> self._fp, msg.preamble
  187. # dash-boundary transport-padding CRLF
  188. print >> self._fp, '--' + boundary
  189. # body-part
  190. if msgtexts:
  191. self._fp.write(msgtexts.pop(0))
  192. # *encapsulation
  193. # --> delimiter transport-padding
  194. # --> CRLF body-part
  195. for body_part in msgtexts:
  196. # delimiter transport-padding CRLF
  197. print >> self._fp, '\n--' + boundary
  198. # body-part
  199. self._fp.write(body_part)
  200. # close-delimiter transport-padding
  201. self._fp.write('\n--' + boundary + '--')
  202. if msg.epilogue is not None:
  203. print >> self._fp
  204. self._fp.write(msg.epilogue)
  205. def _handle_multipart_signed(self, msg):
  206. # The contents of signed parts has to stay unmodified in order to keep
  207. # the signature intact per RFC1847 2.1, so we disable header wrapping.
  208. # RDM: This isn't enough to completely preserve the part, but it helps.
  209. old_maxheaderlen = self._maxheaderlen
  210. try:
  211. self._maxheaderlen = 0
  212. self._handle_multipart(msg)
  213. finally:
  214. self._maxheaderlen = old_maxheaderlen
  215. def _handle_message_delivery_status(self, msg):
  216. # We can't just write the headers directly to self's file object
  217. # because this will leave an extra newline between the last header
  218. # block and the boundary. Sigh.
  219. blocks = []
  220. for part in msg.get_payload():
  221. s = StringIO()
  222. g = self.clone(s)
  223. g.flatten(part, unixfrom=False)
  224. text = s.getvalue()
  225. lines = text.split('\n')
  226. # Strip off the unnecessary trailing empty line
  227. if lines and lines[-1] == '':
  228. blocks.append(NL.join(lines[:-1]))
  229. else:
  230. blocks.append(text)
  231. # Now join all the blocks with an empty line. This has the lovely
  232. # effect of separating each block with an empty line, but not adding
  233. # an extra one after the last one.
  234. self._fp.write(NL.join(blocks))
  235. def _handle_message(self, msg):
  236. s = StringIO()
  237. g = self.clone(s)
  238. # The payload of a message/rfc822 part should be a multipart sequence
  239. # of length 1. The zeroth element of the list should be the Message
  240. # object for the subpart. Extract that object, stringify it, and
  241. # write it out.
  242. # Except, it turns out, when it's a string instead, which happens when
  243. # and only when HeaderParser is used on a message of mime type
  244. # message/rfc822. Such messages are generated by, for example,
  245. # Groupwise when forwarding unadorned messages. (Issue 7970.) So
  246. # in that case we just emit the string body.
  247. payload = msg.get_payload()
  248. if isinstance(payload, list):
  249. g.flatten(msg.get_payload(0), unixfrom=False)
  250. payload = s.getvalue()
  251. self._fp.write(payload)
  252. _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
  253. class DecodedGenerator(Generator):
  254. """Generates a text representation of a message.
  255. Like the Generator base class, except that non-text parts are substituted
  256. with a format string representing the part.
  257. """
  258. def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
  259. """Like Generator.__init__() except that an additional optional
  260. argument is allowed.
  261. Walks through all subparts of a message. If the subpart is of main
  262. type `text', then it prints the decoded payload of the subpart.
  263. Otherwise, fmt is a format string that is used instead of the message
  264. payload. fmt is expanded with the following keywords (in
  265. %(keyword)s format):
  266. type : Full MIME type of the non-text part
  267. maintype : Main MIME type of the non-text part
  268. subtype : Sub-MIME type of the non-text part
  269. filename : Filename of the non-text part
  270. description: Description associated with the non-text part
  271. encoding : Content transfer encoding of the non-text part
  272. The default value for fmt is None, meaning
  273. [Non-text (%(type)s) part of message omitted, filename %(filename)s]
  274. """
  275. Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
  276. if fmt is None:
  277. self._fmt = _FMT
  278. else:
  279. self._fmt = fmt
  280. def _dispatch(self, msg):
  281. for part in msg.walk():
  282. maintype = part.get_content_maintype()
  283. if maintype == 'text':
  284. print >> self, part.get_payload(decode=True)
  285. elif maintype == 'multipart':
  286. # Just skip this
  287. pass
  288. else:
  289. print >> self, self._fmt % {
  290. 'type' : part.get_content_type(),
  291. 'maintype' : part.get_content_maintype(),
  292. 'subtype' : part.get_content_subtype(),
  293. 'filename' : part.get_filename('[no filename]'),
  294. 'description': part.get('Content-Description',
  295. '[no description]'),
  296. 'encoding' : part.get('Content-Transfer-Encoding',
  297. '[no encoding]'),
  298. }
  299. # Helper
  300. _width = len(repr(sys.maxint-1))
  301. _fmt = '%%0%dd' % _width
  302. def _make_boundary(text=None):
  303. # Craft a random boundary. If text is given, ensure that the chosen
  304. # boundary doesn't appear in the text.
  305. token = random.randrange(sys.maxint)
  306. boundary = ('=' * 15) + (_fmt % token) + '=='
  307. if text is None:
  308. return boundary
  309. b = boundary
  310. counter = 0
  311. while True:
  312. cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
  313. if not cre.search(text):
  314. break
  315. b = boundary + '.' + str(counter)
  316. counter += 1
  317. return b