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