/Lib/email/charset.py

http://unladen-swallow.googlecode.com/ · Python · 391 lines · 300 code · 27 blank · 64 comment · 13 complexity · 7e618fcb0b062f2deb396f7bdbdd1177 MD5 · raw file

  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Ben Gertzfield, Barry Warsaw
  3. # Contact: email-sig@python.org
  4. __all__ = [
  5. 'Charset',
  6. 'add_alias',
  7. 'add_charset',
  8. 'add_codec',
  9. ]
  10. import email.base64mime
  11. import email.quoprimime
  12. from email import errors
  13. from email.encoders import encode_7or8bit
  14. # Flags for types of header encodings
  15. QP = 1 # Quoted-Printable
  16. BASE64 = 2 # Base64
  17. SHORTEST = 3 # the shorter of QP and base64, but only for headers
  18. # In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
  19. MISC_LEN = 7
  20. DEFAULT_CHARSET = 'us-ascii'
  21. # Defaults
  22. CHARSETS = {
  23. # input header enc body enc output conv
  24. 'iso-8859-1': (QP, QP, None),
  25. 'iso-8859-2': (QP, QP, None),
  26. 'iso-8859-3': (QP, QP, None),
  27. 'iso-8859-4': (QP, QP, None),
  28. # iso-8859-5 is Cyrillic, and not especially used
  29. # iso-8859-6 is Arabic, also not particularly used
  30. # iso-8859-7 is Greek, QP will not make it readable
  31. # iso-8859-8 is Hebrew, QP will not make it readable
  32. 'iso-8859-9': (QP, QP, None),
  33. 'iso-8859-10': (QP, QP, None),
  34. # iso-8859-11 is Thai, QP will not make it readable
  35. 'iso-8859-13': (QP, QP, None),
  36. 'iso-8859-14': (QP, QP, None),
  37. 'iso-8859-15': (QP, QP, None),
  38. 'iso-8859-16': (QP, QP, None),
  39. 'windows-1252':(QP, QP, None),
  40. 'viscii': (QP, QP, None),
  41. 'us-ascii': (None, None, None),
  42. 'big5': (BASE64, BASE64, None),
  43. 'gb2312': (BASE64, BASE64, None),
  44. 'euc-jp': (BASE64, None, 'iso-2022-jp'),
  45. 'shift_jis': (BASE64, None, 'iso-2022-jp'),
  46. 'iso-2022-jp': (BASE64, None, None),
  47. 'koi8-r': (BASE64, BASE64, None),
  48. 'utf-8': (SHORTEST, BASE64, 'utf-8'),
  49. # We're making this one up to represent raw unencoded 8-bit
  50. '8bit': (None, BASE64, 'utf-8'),
  51. }
  52. # Aliases for other commonly-used names for character sets. Map
  53. # them to the real ones used in email.
  54. ALIASES = {
  55. 'latin_1': 'iso-8859-1',
  56. 'latin-1': 'iso-8859-1',
  57. 'latin_2': 'iso-8859-2',
  58. 'latin-2': 'iso-8859-2',
  59. 'latin_3': 'iso-8859-3',
  60. 'latin-3': 'iso-8859-3',
  61. 'latin_4': 'iso-8859-4',
  62. 'latin-4': 'iso-8859-4',
  63. 'latin_5': 'iso-8859-9',
  64. 'latin-5': 'iso-8859-9',
  65. 'latin_6': 'iso-8859-10',
  66. 'latin-6': 'iso-8859-10',
  67. 'latin_7': 'iso-8859-13',
  68. 'latin-7': 'iso-8859-13',
  69. 'latin_8': 'iso-8859-14',
  70. 'latin-8': 'iso-8859-14',
  71. 'latin_9': 'iso-8859-15',
  72. 'latin-9': 'iso-8859-15',
  73. 'latin_10':'iso-8859-16',
  74. 'latin-10':'iso-8859-16',
  75. 'cp949': 'ks_c_5601-1987',
  76. 'euc_jp': 'euc-jp',
  77. 'euc_kr': 'euc-kr',
  78. 'ascii': 'us-ascii',
  79. }
  80. # Map charsets to their Unicode codec strings.
  81. CODEC_MAP = {
  82. 'gb2312': 'eucgb2312_cn',
  83. 'big5': 'big5_tw',
  84. # Hack: We don't want *any* conversion for stuff marked us-ascii, as all
  85. # sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
  86. # Let that stuff pass through without conversion to/from Unicode.
  87. 'us-ascii': None,
  88. }
  89. # Convenience functions for extending the above mappings
  90. def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
  91. """Add character set properties to the global registry.
  92. charset is the input character set, and must be the canonical name of a
  93. character set.
  94. Optional header_enc and body_enc is either Charset.QP for
  95. quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
  96. the shortest of qp or base64 encoding, or None for no encoding. SHORTEST
  97. is only valid for header_enc. It describes how message headers and
  98. message bodies in the input charset are to be encoded. Default is no
  99. encoding.
  100. Optional output_charset is the character set that the output should be
  101. in. Conversions will proceed from input charset, to Unicode, to the
  102. output charset when the method Charset.convert() is called. The default
  103. is to output in the same character set as the input.
  104. Both input_charset and output_charset must have Unicode codec entries in
  105. the module's charset-to-codec mapping; use add_codec(charset, codecname)
  106. to add codecs the module does not know about. See the codecs module's
  107. documentation for more information.
  108. """
  109. if body_enc == SHORTEST:
  110. raise ValueError('SHORTEST not allowed for body_enc')
  111. CHARSETS[charset] = (header_enc, body_enc, output_charset)
  112. def add_alias(alias, canonical):
  113. """Add a character set alias.
  114. alias is the alias name, e.g. latin-1
  115. canonical is the character set's canonical name, e.g. iso-8859-1
  116. """
  117. ALIASES[alias] = canonical
  118. def add_codec(charset, codecname):
  119. """Add a codec that map characters in the given charset to/from Unicode.
  120. charset is the canonical name of a character set. codecname is the name
  121. of a Python codec, as appropriate for the second argument to the unicode()
  122. built-in, or to the encode() method of a Unicode string.
  123. """
  124. CODEC_MAP[charset] = codecname
  125. class Charset:
  126. """Map character sets to their email properties.
  127. This class provides information about the requirements imposed on email
  128. for a specific character set. It also provides convenience routines for
  129. converting between character sets, given the availability of the
  130. applicable codecs. Given a character set, it will do its best to provide
  131. information on how to use that character set in an email in an
  132. RFC-compliant way.
  133. Certain character sets must be encoded with quoted-printable or base64
  134. when used in email headers or bodies. Certain character sets must be
  135. converted outright, and are not allowed in email. Instances of this
  136. module expose the following information about a character set:
  137. input_charset: The initial character set specified. Common aliases
  138. are converted to their `official' email names (e.g. latin_1
  139. is converted to iso-8859-1). Defaults to 7-bit us-ascii.
  140. header_encoding: If the character set must be encoded before it can be
  141. used in an email header, this attribute will be set to
  142. Charset.QP (for quoted-printable), Charset.BASE64 (for
  143. base64 encoding), or Charset.SHORTEST for the shortest of
  144. QP or BASE64 encoding. Otherwise, it will be None.
  145. body_encoding: Same as header_encoding, but describes the encoding for the
  146. mail message's body, which indeed may be different than the
  147. header encoding. Charset.SHORTEST is not allowed for
  148. body_encoding.
  149. output_charset: Some character sets must be converted before the can be
  150. used in email headers or bodies. If the input_charset is
  151. one of them, this attribute will contain the name of the
  152. charset output will be converted to. Otherwise, it will
  153. be None.
  154. input_codec: The name of the Python codec used to convert the
  155. input_charset to Unicode. If no conversion codec is
  156. necessary, this attribute will be None.
  157. output_codec: The name of the Python codec used to convert Unicode
  158. to the output_charset. If no conversion codec is necessary,
  159. this attribute will have the same value as the input_codec.
  160. """
  161. def __init__(self, input_charset=DEFAULT_CHARSET):
  162. # RFC 2046, $4.1.2 says charsets are not case sensitive. We coerce to
  163. # unicode because its .lower() is locale insensitive. If the argument
  164. # is already a unicode, we leave it at that, but ensure that the
  165. # charset is ASCII, as the standard (RFC XXX) requires.
  166. try:
  167. if isinstance(input_charset, unicode):
  168. input_charset.encode('ascii')
  169. else:
  170. input_charset = unicode(input_charset, 'ascii')
  171. except UnicodeError:
  172. raise errors.CharsetError(input_charset)
  173. input_charset = input_charset.lower()
  174. # Set the input charset after filtering through the aliases
  175. self.input_charset = ALIASES.get(input_charset, input_charset)
  176. # We can try to guess which encoding and conversion to use by the
  177. # charset_map dictionary. Try that first, but let the user override
  178. # it.
  179. henc, benc, conv = CHARSETS.get(self.input_charset,
  180. (SHORTEST, BASE64, None))
  181. if not conv:
  182. conv = self.input_charset
  183. # Set the attributes, allowing the arguments to override the default.
  184. self.header_encoding = henc
  185. self.body_encoding = benc
  186. self.output_charset = ALIASES.get(conv, conv)
  187. # Now set the codecs. If one isn't defined for input_charset,
  188. # guess and try a Unicode codec with the same name as input_codec.
  189. self.input_codec = CODEC_MAP.get(self.input_charset,
  190. self.input_charset)
  191. self.output_codec = CODEC_MAP.get(self.output_charset,
  192. self.output_charset)
  193. def __str__(self):
  194. return self.input_charset.lower()
  195. __repr__ = __str__
  196. def __eq__(self, other):
  197. return str(self) == str(other).lower()
  198. def __ne__(self, other):
  199. return not self.__eq__(other)
  200. def get_body_encoding(self):
  201. """Return the content-transfer-encoding used for body encoding.
  202. This is either the string `quoted-printable' or `base64' depending on
  203. the encoding used, or it is a function in which case you should call
  204. the function with a single argument, the Message object being
  205. encoded. The function should then set the Content-Transfer-Encoding
  206. header itself to whatever is appropriate.
  207. Returns "quoted-printable" if self.body_encoding is QP.
  208. Returns "base64" if self.body_encoding is BASE64.
  209. Returns "7bit" otherwise.
  210. """
  211. assert self.body_encoding != SHORTEST
  212. if self.body_encoding == QP:
  213. return 'quoted-printable'
  214. elif self.body_encoding == BASE64:
  215. return 'base64'
  216. else:
  217. return encode_7or8bit
  218. def convert(self, s):
  219. """Convert a string from the input_codec to the output_codec."""
  220. if self.input_codec != self.output_codec:
  221. return unicode(s, self.input_codec).encode(self.output_codec)
  222. else:
  223. return s
  224. def to_splittable(self, s):
  225. """Convert a possibly multibyte string to a safely splittable format.
  226. Uses the input_codec to try and convert the string to Unicode, so it
  227. can be safely split on character boundaries (even for multibyte
  228. characters).
  229. Returns the string as-is if it isn't known how to convert it to
  230. Unicode with the input_charset.
  231. Characters that could not be converted to Unicode will be replaced
  232. with the Unicode replacement character U+FFFD.
  233. """
  234. if isinstance(s, unicode) or self.input_codec is None:
  235. return s
  236. try:
  237. return unicode(s, self.input_codec, 'replace')
  238. except LookupError:
  239. # Input codec not installed on system, so return the original
  240. # string unchanged.
  241. return s
  242. def from_splittable(self, ustr, to_output=True):
  243. """Convert a splittable string back into an encoded string.
  244. Uses the proper codec to try and convert the string from Unicode back
  245. into an encoded format. Return the string as-is if it is not Unicode,
  246. or if it could not be converted from Unicode.
  247. Characters that could not be converted from Unicode will be replaced
  248. with an appropriate character (usually '?').
  249. If to_output is True (the default), uses output_codec to convert to an
  250. encoded format. If to_output is False, uses input_codec.
  251. """
  252. if to_output:
  253. codec = self.output_codec
  254. else:
  255. codec = self.input_codec
  256. if not isinstance(ustr, unicode) or codec is None:
  257. return ustr
  258. try:
  259. return ustr.encode(codec, 'replace')
  260. except LookupError:
  261. # Output codec not installed
  262. return ustr
  263. def get_output_charset(self):
  264. """Return the output character set.
  265. This is self.output_charset if that is not None, otherwise it is
  266. self.input_charset.
  267. """
  268. return self.output_charset or self.input_charset
  269. def encoded_header_len(self, s):
  270. """Return the length of the encoded header string."""
  271. cset = self.get_output_charset()
  272. # The len(s) of a 7bit encoding is len(s)
  273. if self.header_encoding == BASE64:
  274. return email.base64mime.base64_len(s) + len(cset) + MISC_LEN
  275. elif self.header_encoding == QP:
  276. return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN
  277. elif self.header_encoding == SHORTEST:
  278. lenb64 = email.base64mime.base64_len(s)
  279. lenqp = email.quoprimime.header_quopri_len(s)
  280. return min(lenb64, lenqp) + len(cset) + MISC_LEN
  281. else:
  282. return len(s)
  283. def header_encode(self, s, convert=False):
  284. """Header-encode a string, optionally converting it to output_charset.
  285. If convert is True, the string will be converted from the input
  286. charset to the output charset automatically. This is not useful for
  287. multibyte character sets, which have line length issues (multibyte
  288. characters must be split on a character, not a byte boundary); use the
  289. high-level Header class to deal with these issues. convert defaults
  290. to False.
  291. The type of encoding (base64 or quoted-printable) will be based on
  292. self.header_encoding.
  293. """
  294. cset = self.get_output_charset()
  295. if convert:
  296. s = self.convert(s)
  297. # 7bit/8bit encodings return the string unchanged (modulo conversions)
  298. if self.header_encoding == BASE64:
  299. return email.base64mime.header_encode(s, cset)
  300. elif self.header_encoding == QP:
  301. return email.quoprimime.header_encode(s, cset, maxlinelen=None)
  302. elif self.header_encoding == SHORTEST:
  303. lenb64 = email.base64mime.base64_len(s)
  304. lenqp = email.quoprimime.header_quopri_len(s)
  305. if lenb64 < lenqp:
  306. return email.base64mime.header_encode(s, cset)
  307. else:
  308. return email.quoprimime.header_encode(s, cset, maxlinelen=None)
  309. else:
  310. return s
  311. def body_encode(self, s, convert=True):
  312. """Body-encode a string and convert it to output_charset.
  313. If convert is True (the default), the string will be converted from
  314. the input charset to output charset automatically. Unlike
  315. header_encode(), there are no issues with byte boundaries and
  316. multibyte charsets in email bodies, so this is usually pretty safe.
  317. The type of encoding (base64 or quoted-printable) will be based on
  318. self.body_encoding.
  319. """
  320. if convert:
  321. s = self.convert(s)
  322. # 7bit/8bit encodings return the string unchanged (module conversions)
  323. if self.body_encoding is BASE64:
  324. return email.base64mime.body_encode(s)
  325. elif self.body_encoding is QP:
  326. return email.quoprimime.body_encode(s)
  327. else:
  328. return s