]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
mimedecode.py version 2.0.0d.
[mimedecode.git] / mimedecode.py
1 #! /usr/local/bin/python -O
2 """Decode MIME message.
3
4 Author: Oleg Broytmann <phd@phd.pp.ru>
5 Copyright: (C) 2001-2002 PhiloSoft Design
6 License: GPL
7 """
8
9 __version__ = "2.0.0"
10 __copyright__ = "Copyright (C) 2001-2002 PhiloSoft Design"
11
12
13 import sys, os
14 import email
15
16 try:
17    from cStringIO import StringIO
18 except ImportError:
19    from StringIO import StringIO
20
21
22 import socket
23 host_name = socket.gethostname()
24
25 me = os.path.basename(sys.argv[0])
26
27
28 def version(exit=1):
29    sys.stdout.write("""\
30 BroytMann mimedecode.py version %s, %s
31 """ % (__version__, __copyright__))
32    if exit: sys.exit(0)
33
34
35 def usage(code=0):
36    version(0)
37    sys.stdout.write("""\
38 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [filename]
39 """ % me)
40    sys.exit(code)
41
42
43 def output(s, outfile = sys.stdout):
44    outfile.write(s)
45
46 def output_headers(msg, outfile = sys.stdout):
47    unix_from = msg.get_unixfrom()
48    if unix_from:
49       output(unix_from + os.linesep)
50    for key, value in msg.items():
51       output("%s: %s\n" % (key, value), outfile)
52    output("\n", outfile) # End of headers
53
54
55 def recode(s, charset):
56    return unicode(s, charset, "replace").encode(GlobalOptions.default_charset, "replace")
57
58
59 def recode2(s, charset):
60    if charset and charset <> GlobalOptions.default_charset:
61       s = recode(s, charset)
62    return s
63
64
65 def _decode_header(s):
66    """Return a decoded string according to RFC 2047.
67    NOTE: This is almost the same as email.Utils.decode.
68    """
69    from types import ListType
70    import email.Header
71
72    L = email.Header.decode_header(s)
73    if not isinstance(L, ListType):
74       # s wasn't decoded
75       return s
76
77    rtn = []
78    for atom, charset in L:
79       if charset is None:
80          rtn.append(atom)
81       else:
82          rtn.append(recode2(atom, charset))
83       rtn.append(' ')
84    del rtn[-1] # remove the last space
85
86    # Now that we've decoded everything, we just need to join all the parts
87    # together into the final string.
88    return ''.join(rtn)
89
90
91 def decode_header(msg, header):
92    "Decode mail header (if exists) and put it back, if it was encoded"
93
94    if msg.has_key(header):
95       value = msg[header]
96       new_value = _decode_header(value)
97       if new_value <> value: # do not bother to touch msg if not changed
98          set_header(msg, header, new_value)
99
100
101 def _decode_header_param(s):
102    return recode2(s[2], s[0])
103
104
105 def decode_header_param(msg, header, param):
106    "Decode mail header's parameter (if exists) and put it back, if it was encoded"
107
108    if msg.has_key(header):
109       value = msg.get_param(param, header=header)
110       if value:
111          from types import TupleType
112          if isinstance(value, TupleType):
113             new_value = _decode_header_param(value)
114          else:
115             new_value = _decode_header(value)
116          if new_value <> value: # do not bother to touch msg if not changed
117             msg.set_param(param, new_value, header)
118
119
120 def decode_headers(msg):
121    "Decode message headers according to global options"
122
123    for header in GlobalOptions.decode_headers:
124       decode_header(msg, header)
125
126    for header, param in GlobalOptions.decode_header_params:
127       decode_header_param(msg, header, param)
128
129
130 def set_header(msg, header, value):
131    "Replace header"
132
133    if msg.has_key(header):
134       msg.replace_header(header, value)
135    else:
136       msg[header] = value
137
138
139 def set_content_type(msg, newtype, charset=None):
140    msg.set_type(newtype)
141
142    if charset:
143       msg.set_param("charset", charset, "Content-Type")
144
145
146
147 caps = None # Globally stored mailcap database; initialized only if needed
148
149 def decode_body(msg, s):
150    "Decode body to plain text using first copiousoutput filter from mailcap"
151
152    import mailcap, tempfile
153
154    global caps
155    if caps is None:
156       caps = mailcap.getcaps()
157
158    content_type = msg.get_content_type()
159    filename = tempfile.mktemp()
160    command = None
161
162    entries = mailcap.lookup(caps, content_type, "view")
163    for entry in entries:
164       if entry.has_key('copiousoutput'):
165          if entry.has_key('test'):
166             test = mailcap.subst(entry['test'], content_type, filename)
167             if test and os.system(test) != 0:
168                continue
169          command = mailcap.subst(entry["view"], content_type, filename)
170          break
171
172    if not command:
173       return s
174
175    file = open(filename, 'w')
176    file.write(s)
177    file.close()
178
179    pipe = os.popen(command, 'r')
180    s = pipe.read()
181    pipe.close()
182    os.remove(filename)
183
184    set_content_type(msg, "text/plain")
185    msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
186
187    return s
188
189
190 def recode_charset(msg, s):
191    "Recode charset of the message to the default charset"
192
193    save_charset = charset = msg.get_content_charset()
194    if charset and charset <> GlobalOptions.default_charset:
195       s = recode2(s, charset)
196       content_type = msg.get_content_type()
197       set_content_type(msg, content_type, GlobalOptions.default_charset)
198       msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_charset, host_name, me)
199    return s
200
201
202 def totext(msg, instring):
203    "Convert instring content to text"
204
205    if msg.is_multipart(): # Recursively decode all parts of the multipart message
206       newfile = StringIO(str(msg))
207       newfile.seek(0)
208       decode_file(newfile)
209       return
210
211    # Decode body and recode charset
212    s = decode_body(msg, instring)
213    if GlobalOptions.recode_charset:
214       s = recode_charset(msg, s)
215
216    output_headers(msg)
217    output(s)
218
219
220 def decode_part(msg):
221    "Decode one part of the message"
222
223    decode_headers(msg)
224    encoding = msg["Content-Transfer-Encoding"]
225
226    if encoding in (None, '', '7bit', '8bit', 'binary'):
227       outstring = str(msg.get_payload())
228    else: # Decode from transfer ecoding to text or binary form
229       outstring = str(msg.get_payload(decode=1))
230       set_header(msg, "Content-Transfer-Encoding", "8bit")
231       msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
232
233    # Test all mask lists and find what to do with this content type
234    masks = []
235    ctype = msg.get_content_type()
236    if ctype:
237       masks.append(ctype)
238    mtype = msg.get_content_maintype()
239    if mtype:
240       masks.append(mtype + '/*')
241    masks.append('*/*')
242
243    for content_type in masks:
244       if content_type in GlobalOptions.totext_mask:
245          totext(msg, outstring)
246          return
247       elif content_type in GlobalOptions.binary_mask:
248          output_headers(msg)
249          output(outstring)
250          return
251       elif content_type in GlobalOptions.ignore_mask:
252          output_headers(msg)
253          output("\nMessage body of type `%s' skipped.\n" % content_type)
254          return
255       elif content_type in GlobalOptions.error_mask:
256          raise ValueError, "content type `%s' prohibited" % content_type
257
258    # Neither content type nor masks were listed - decode by default
259    totext(msg, outstring)
260
261
262 def decode_file(infile):
263    "Decode the entire message"
264
265    msg = email.message_from_file(infile)
266    boundary = msg.get_boundary()
267
268    if msg.is_multipart():
269       decode_headers(msg)
270       output_headers(msg)
271
272       if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
273          output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
274
275       for subpart in msg.get_payload():
276          output("\n--%s\n" % boundary)
277          decode_part(subpart)
278
279       output("\n--%s--\n" % boundary)
280
281       if msg.epilogue:
282          output(msg.epilogue)
283
284    else:
285       if msg.has_key("Content-Type"): # Simple one-part message - decode it
286          decode_part(msg)
287
288       else: # Not a message, just text - copy it literally
289          output(str(msg))
290
291
292 class GlobalOptions:
293    default_charset = sys.getdefaultencoding()
294    recode_charset = 1 # recode charset of message body
295
296    decode_headers = ["Subject", "From"] # A list of headers to decode
297    decode_header_params = [("Content-Type", "name"),
298       ("Content-Disposition", "filename")
299    ] # A list of headers' parameters to decode
300
301    totext_mask = [] # A list of content-types to decode
302    binary_mask = [] # A list to pass through
303    ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
304    error_mask = []  # Raise error if encounter one of these
305
306
307 def init():
308    from getopt import getopt, GetoptError
309
310    try:
311       options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
312          ['help', 'version'])
313    except GetoptError:
314       usage(1)
315
316    for option, value in options:
317       if option == '-h':
318          usage()
319       elif option == '--help':
320          usage()
321       elif option == '-V':
322          version()
323       elif option == '--version':
324          version()
325       elif option == '-c':
326          GlobalOptions.recode_charset = 1
327       elif option == '-C':
328          GlobalOptions.recode_charset = 0
329       elif option == '-f':
330          GlobalOptions.default_charset = value
331       elif option == '-d':
332          GlobalOptions.decode_headers.append(value)
333       elif option == '-D':
334          GlobalOptions.decode_headers = []
335       elif option == '-p':
336          GlobalOptions.decode_header_params.append(value.split(':', 1))
337       elif option == '-P':
338          GlobalOptions.decode_header_params = []
339       elif option == '-t':
340          GlobalOptions.totext_mask.append(value)
341       elif option == '-b':
342          GlobalOptions.binary_mask.append(value)
343       elif option == '-i':
344          GlobalOptions.ignore_mask.append(value)
345       elif option == '-e':
346          GlobalOptions.error_mask.append(value)
347       else:
348          usage(1)
349
350    return arguments
351
352
353 if __name__ == "__main__":
354    arguments = init()
355
356    if len(arguments) == 0:
357       infile = sys.stdin
358    elif len(arguments) <> 1:
359       usage(1)
360    elif arguments[0] == '-':
361       infile = sys.stdin
362    else:
363       infile = open(arguments[0], 'r')
364
365    decode_file(infile)