blob: f09affac39986270414054656db24a22d3de0086 [file] [log] [blame]
Barry Warsaw409a4c02002-04-10 21:01:31 +00001# Copyright (C) 2001,2002 Python Software Foundation
Barry Warsawba925802001-09-23 03:17:28 +00002# Author: barry@zope.com (Barry Warsaw)
3
4"""Module containing encoding functions for Image.Image and Text.Text.
5"""
6
7import base64
8from quopri import encodestring as _encodestring
9
10
Barry Warsawe968ead2001-10-04 17:05:11 +000011
Barry Warsawba925802001-09-23 03:17:28 +000012# Helpers
13def _qencode(s):
Barry Warsaw409a4c02002-04-10 21:01:31 +000014 enc = _encodestring(s, quotetabs=1)
15 # Must encode spaces, which quopri.encodestring() doesn't do
16 return enc.replace(' ', '=20')
Barry Warsawba925802001-09-23 03:17:28 +000017
Barry Warsaw6f70c412001-09-26 05:26:22 +000018
Barry Warsawba925802001-09-23 03:17:28 +000019def _bencode(s):
20 # We can't quite use base64.encodestring() since it tacks on a "courtesy
21 # newline". Blech!
22 if not s:
23 return s
24 hasnewline = (s[-1] == '\n')
25 value = base64.encodestring(s)
26 if not hasnewline and value[-1] == '\n':
27 return value[:-1]
28 return value
29
30
Barry Warsawe968ead2001-10-04 17:05:11 +000031
Barry Warsawba925802001-09-23 03:17:28 +000032def encode_base64(msg):
33 """Encode the message's payload in Base64.
34
35 Also, add an appropriate Content-Transfer-Encoding: header.
36 """
37 orig = msg.get_payload()
38 encdata = _bencode(orig)
39 msg.set_payload(encdata)
40 msg['Content-Transfer-Encoding'] = 'base64'
41
42
Barry Warsawe968ead2001-10-04 17:05:11 +000043
Barry Warsawba925802001-09-23 03:17:28 +000044def encode_quopri(msg):
45 """Encode the message's payload in Quoted-Printable.
46
47 Also, add an appropriate Content-Transfer-Encoding: header.
48 """
49 orig = msg.get_payload()
50 encdata = _qencode(orig)
51 msg.set_payload(encdata)
52 msg['Content-Transfer-Encoding'] = 'quoted-printable'
53
54
Barry Warsawe968ead2001-10-04 17:05:11 +000055
Barry Warsawba925802001-09-23 03:17:28 +000056def encode_7or8bit(msg):
57 """Set the Content-Transfer-Encoding: header to 7bit or 8bit."""
58 orig = msg.get_payload()
Barry Warsaw409a4c02002-04-10 21:01:31 +000059 if orig is None:
60 # There's no payload. For backwards compatibility we use 7bit
61 msg['Content-Transfer-Encoding'] = '7bit'
62 return
Barry Warsawba925802001-09-23 03:17:28 +000063 # We play a trick to make this go fast. If encoding to ASCII succeeds, we
64 # know the data must be 7bit, otherwise treat it as 8bit.
65 try:
66 orig.encode('ascii')
67 except UnicodeError:
68 msg['Content-Transfer-Encoding'] = '8bit'
69 else:
70 msg['Content-Transfer-Encoding'] = '7bit'
71
72
Barry Warsawe968ead2001-10-04 17:05:11 +000073
Barry Warsawba925802001-09-23 03:17:28 +000074def encode_noop(msg):
75 """Do nothing."""