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