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