]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Add a few comments
[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] [--remove-params=header] [-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 in gopts.remove_all_params:
104         value = msg[header]
105         if value is None: # No such header
106             continue
107         if ';' not in value: # There are no parameters
108             continue
109         del msg[header] # Delete all such headers
110         # Get the value without parameters and set it back
111         msg[header] = value.split(';')[0].strip()
112
113     for header, param in gopts.remove_header_params:
114         msg.del_param(param, header)
115
116     for header in gopts.decode_headers:
117         decode_header(msg, header)
118
119     for header, param in gopts.decode_header_params:
120         decode_header_param(msg, header, param)
121
122
123 def set_header(msg, header, value):
124     "Replace header"
125
126     if msg.has_key(header):
127         msg.replace_header(header, value)
128     else:
129         msg[header] = value
130
131
132 def set_content_type(msg, newtype, charset=None):
133     msg.set_type(newtype)
134
135     if charset:
136         msg.set_param("charset", charset, "Content-Type")
137
138
139 caps = None # Globally stored mailcap database; initialized only if needed
140
141 def decode_body(msg, s):
142     "Decode body to plain text using first copiousoutput filter from mailcap"
143
144     import mailcap, tempfile
145
146     global caps
147     if caps is None:
148         caps = mailcap.getcaps()
149
150     content_type = msg.get_content_type()
151     filename = tempfile.mktemp()
152     command = None
153
154     entries = mailcap.lookup(caps, content_type, "view")
155     for entry in entries:
156         if entry.has_key('copiousoutput'):
157             if entry.has_key('test'):
158                 test = mailcap.subst(entry['test'], content_type, filename)
159                 if test and os.system(test) != 0:
160                     continue
161             command = mailcap.subst(entry["view"], content_type, filename)
162             break
163
164     if not command:
165         return s
166
167     file = open(filename, 'w')
168     file.write(s)
169     file.close()
170
171     pipe = os.popen(command, 'r')
172     s = pipe.read()
173     pipe.close()
174     os.remove(filename)
175
176     set_content_type(msg, "text/plain")
177     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
178
179     return s
180
181
182 def recode_charset(msg, s):
183     "Recode charset of the message to the default charset"
184
185     save_charset = charset = msg.get_content_charset()
186     if charset and charset.lower() <> gopts.default_encoding:
187         s = recode_if_needed(s, charset)
188         content_type = msg.get_content_type()
189         set_content_type(msg, content_type, gopts.default_encoding)
190         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
191     return s
192
193
194 def totext(msg, instring):
195     "Convert instring content to text"
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_multipart(msg):
249     "Decode multipart"
250
251     decode_headers(msg)
252     output_headers(msg)
253
254     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
255         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
256
257     boundary = msg.get_boundary()
258
259     for subpart in msg.get_payload():
260         if boundary:
261             output("\n--%s\n" % boundary)
262
263         # Recursively decode all parts of the subpart
264         decode_message(subpart)
265
266     if boundary:
267         output("\n--%s--\n" % boundary)
268
269     if msg.epilogue:
270         output(msg.epilogue)
271
272
273 def decode_message(msg):
274     "Decode message"
275
276     if msg.is_multipart():
277         decode_multipart(msg)
278     elif len(msg): # Simple one-part message (there are headers) - decode it
279         decode_part(msg)
280     else: # Not a message, just text - copy it literally
281         output(msg.as_string())
282
283
284 class GlobalOptions:
285     from m_lib.defenc import default_encoding
286     recode_charset = 1 # recode charset of message body
287
288     host_name = None
289
290     # A list of headers to decode
291     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
292                       "Subject"]
293
294     # A list of headers parameters to decode
295     decode_header_params = [
296         ("Content-Type", "name"),
297         ("Content-Disposition", "filename"),
298     ]
299
300     # A list of headers to remove
301     remove_headers = []
302     # A list of headers parameters to remove
303     remove_header_params = []
304     # A list of headers to be stripped of all parameters
305     remove_all_params = []
306
307     totext_mask = [] # A list of content-types to decode
308     binary_mask = [] # A list to pass through
309     ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
310     error_mask = []  # Raise error if encounter one of these
311
312     input_filename = None
313     output_filename = None
314
315 gopts = GlobalOptions
316
317
318 def get_opt():
319     from getopt import getopt, GetoptError
320
321     try:
322         options, arguments = getopt(sys.argv[1:],
323             'hVcCDPH:f:d:p:r:R:b:e:i:t:o:',
324             ['help', 'version', 'host=', 'remove-params='])
325     except GetoptError:
326         usage(1)
327
328     for option, value in options:
329         if option in ('-h', '--help'):
330             usage()
331         elif option in ('-V', '--version'):
332             version()
333         elif option == '-c':
334             gopts.recode_charset = 1
335         elif option == '-C':
336             gopts.recode_charset = 0
337         elif option in ('-H', '--host'):
338             gopts.host_name = value
339         elif option == '-f':
340             gopts.default_encoding = value
341         elif option == '-d':
342             gopts.decode_headers.append(value)
343         elif option == '-D':
344             gopts.decode_headers = []
345         elif option == '-p':
346             gopts.decode_header_params.append(value.split(':', 1))
347         elif option == '-P':
348             gopts.decode_header_params = []
349         elif option == '-r':
350             gopts.remove_headers.append(value)
351         elif option == '-R':
352             gopts.remove_header_params.append(value.split(':', 1))
353         elif option == '--remove-params':
354             gopts.remove_all_params.append(value)
355         elif option == '-t':
356             gopts.totext_mask.append(value)
357         elif option == '-b':
358             gopts.binary_mask.append(value)
359         elif option == '-i':
360             gopts.ignore_mask.append(value)
361         elif option == '-e':
362             gopts.error_mask.append(value)
363         elif option == '-o':
364             gopts.output_filename = value
365         else:
366             usage(1)
367
368     return arguments
369
370
371 if __name__ == "__main__":
372     arguments = get_opt()
373
374     la = len(arguments)
375     if la == 0:
376         gopts.input_filename = '-'
377         infile = sys.stdin
378         if gopts.output_filename:
379             outfile = open(gopts.output_filename, 'w')
380         else:
381             gopts.output_filename = '-'
382             outfile = sys.stdout
383     elif la in (1, 2):
384         if (arguments[0] == '-'):
385             gopts.input_filename = '-'
386             infile = sys.stdin
387         else:
388             gopts.input_filename = arguments[0]
389             infile = open(arguments[0], 'r')
390         if la == 1:
391             if gopts.output_filename:
392                 outfile = open(gopts.output_filename, 'w')
393             else:
394                 gopts.output_filename = '-'
395                 outfile = sys.stdout
396         elif la == 2:
397             if gopts.output_filename:
398                 usage(1, 'Too many output filenames')
399             if (arguments[1] == '-'):
400                 gopts.output_filename = '-'
401                 outfile = sys.stdout
402             else:
403                 gopts.output_filename = arguments[1]
404                 outfile = open(arguments[1], 'w')
405     else:
406         usage(1, 'Too many arguments')
407
408     if (infile is sys.stdin) and sys.stdin.isatty():
409         if (outfile is sys.stdout) and sys.stdout.isatty():
410             usage()
411         usage(1, 'Filtering from console is forbidden')
412
413     if not gopts.host_name:
414         import socket
415         gopts.host_name = socket.gethostname()
416
417     gopts.outfile = outfile
418     output = outfile.write
419
420     try:
421         decode_message(email.message_from_file(infile))
422     finally:
423         infile.close()
424         outfile.close()