]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
Remove option --remove-params
[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 header1[,h2,...]|*[,-h1,...]] [-p header1[,h2,h3,...]:param1[,p2,p3,...]] [-r header1[,h2,...]|*[,-h1,...]] [-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 _get_exceptions(list):
98     return [x[1:].lower() for x in list[1:] if x[0]=='-']
99
100 def _decode_headers_params(msg, header, decode_all_params, param_list):
101     if decode_all_params:
102         params = msg.get_params(header=header)
103         if params:
104             for param, value in params:
105                 if param not in param_list:
106                     decode_header_param(msg, header, param)
107     else:
108         for param in param_list:
109             decode_header_param(msg, header, param)
110
111 def decode_headers(msg):
112     "Decode message headers according to global options"
113
114     for header_list in gopts.remove_headers:
115         header_list = header_list.split(',')
116         if header_list[0] == '*': # Remove all headers except listed
117             header_list = _get_exceptions(header_list)
118             for header in msg.keys():
119                 if header.lower() not in header_list:
120                     del msg[header]
121         else: # Remove listed headers
122             for header in header_list:
123                 del msg[header]
124
125     #for header in gopts.remove_all_params:
126     #    value = msg[header]
127     #    if value is None: # No such header
128     #        continue
129     #    if ';' not in value: # There are no parameters
130     #        continue
131     #    del msg[header] # Delete all such headers
132     #    # Get the value without parameters and set it back
133     #    msg[header] = value.split(';')[0].strip()
134
135     for header, param in gopts.remove_header_params:
136         msg.del_param(param, header)
137
138     for header_list in gopts.decode_headers:
139         header_list = header_list.split(',')
140         if header_list[0] == '*': # Decode all headers except listed
141             header_list = _get_exceptions(header_list)
142             for header in msg.keys():
143                 if header.lower() not in header_list:
144                     decode_header(msg, header)
145         else: # Decode listed headers
146             for header in header_list:
147                 decode_header(msg, header)
148
149     for header_list, param_list in gopts.decode_header_params:
150         header_list = header_list.split(',')
151         param_list = param_list.split(',')
152         decode_all_params = param_list[0] == '*' # Decode all params except listed
153         if decode_all_params:
154             param_list = _get_exceptions(param_list)
155         if header_list[0] == '*': # Decode for all headers except listed
156             header_list = _get_exceptions(header_list)
157             for header in msg.keys():
158                 if header.lower() not in header_list:
159                     _decode_headers_params(msg, header, decode_all_params, param_list)
160         else: # Decode for listed headers
161             for header in header_list:
162                 _decode_headers_params(msg, header, decode_all_params, param_list)
163
164
165 def set_header(msg, header, value):
166     "Replace header"
167
168     if msg.has_key(header):
169         msg.replace_header(header, value)
170     else:
171         msg[header] = value
172
173
174 def set_content_type(msg, newtype, charset=None):
175     msg.set_type(newtype)
176
177     if charset:
178         msg.set_param("charset", charset, "Content-Type")
179
180
181 caps = None # Globally stored mailcap database; initialized only if needed
182
183 def decode_body(msg, s):
184     "Decode body to plain text using first copiousoutput filter from mailcap"
185
186     import mailcap, tempfile
187
188     global caps
189     if caps is None:
190         caps = mailcap.getcaps()
191
192     content_type = msg.get_content_type()
193     filename = tempfile.mktemp()
194     command = None
195
196     entries = mailcap.lookup(caps, content_type, "view")
197     for entry in entries:
198         if entry.has_key('copiousoutput'):
199             if entry.has_key('test'):
200                 test = mailcap.subst(entry['test'], content_type, filename)
201                 if test and os.system(test) != 0:
202                     continue
203             command = mailcap.subst(entry["view"], content_type, filename)
204             break
205
206     if not command:
207         return s
208
209     file = open(filename, 'w')
210     file.write(s)
211     file.close()
212
213     pipe = os.popen(command, 'r')
214     s = pipe.read()
215     pipe.close()
216     os.remove(filename)
217
218     set_content_type(msg, "text/plain")
219     msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
220
221     return s
222
223
224 def recode_charset(msg, s):
225     "Recode charset of the message to the default charset"
226
227     save_charset = charset = msg.get_content_charset()
228     if charset and charset.lower() <> gopts.default_encoding:
229         s = recode_if_needed(s, charset)
230         content_type = msg.get_content_type()
231         set_content_type(msg, content_type, gopts.default_encoding)
232         msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
233     return s
234
235
236 def totext(msg, instring):
237     "Convert instring content to text"
238
239     # Decode body and recode charset
240     s = decode_body(msg, instring)
241     if gopts.recode_charset:
242         s = recode_charset(msg, s)
243
244     output_headers(msg)
245     output(s)
246
247
248 def decode_part(msg):
249     "Decode one part of the message"
250
251     decode_headers(msg)
252     encoding = msg["Content-Transfer-Encoding"]
253
254     if encoding in (None, '', '7bit', '8bit', 'binary'):
255         outstring = str(msg.get_payload())
256     else: # Decode from transfer ecoding to text or binary form
257         outstring = str(msg.get_payload(decode=1))
258         set_header(msg, "Content-Transfer-Encoding", "8bit")
259         msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
260
261     # Test all mask lists and find what to do with this content type
262     masks = []
263     ctype = msg.get_content_type()
264     if ctype:
265         masks.append(ctype)
266     mtype = msg.get_content_maintype()
267     if mtype:
268         masks.append(mtype + '/*')
269     masks.append('*/*')
270
271     for content_type in masks:
272         if content_type in gopts.totext_mask:
273             totext(msg, outstring)
274             return
275         elif content_type in gopts.binary_mask:
276             output_headers(msg)
277             output(outstring)
278             return
279         elif content_type in gopts.ignore_mask:
280             output_headers(msg)
281             output("\nMessage body of type `%s' skipped.\n" % content_type)
282             return
283         elif content_type in gopts.error_mask:
284             raise ValueError, "content type `%s' prohibited" % content_type
285
286     # Neither content type nor masks were listed - decode by default
287     totext(msg, outstring)
288
289
290 def decode_multipart(msg):
291     "Decode multipart"
292
293     decode_headers(msg)
294     output_headers(msg)
295
296     if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
297         output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
298
299     boundary = msg.get_boundary()
300
301     for subpart in msg.get_payload():
302         if boundary:
303             output("\n--%s\n" % boundary)
304
305         # Recursively decode all parts of the subpart
306         decode_message(subpart)
307
308     if boundary:
309         output("\n--%s--\n" % boundary)
310
311     if msg.epilogue:
312         output(msg.epilogue)
313
314
315 def decode_message(msg):
316     "Decode message"
317
318     if msg.is_multipart():
319         decode_multipart(msg)
320     elif len(msg): # Simple one-part message (there are headers) - decode it
321         decode_part(msg)
322     else: # Not a message, just text - copy it literally
323         output(msg.as_string())
324
325
326 class GlobalOptions:
327     from m_lib.defenc import default_encoding
328     recode_charset = 1 # recode charset of message body
329
330     host_name = None
331
332     # A list of headers to decode
333     decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
334                       "Subject"]
335
336     # A list of headers parameters to decode
337     decode_header_params = [
338         ("Content-Type", "name"),
339         ("Content-Disposition", "filename"),
340     ]
341
342     # A list of headers to remove
343     remove_headers = []
344     # A list of headers parameters to remove
345     remove_header_params = []
346
347     totext_mask = [] # A list of content-types to decode
348     binary_mask = [] # A list to pass through
349     ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
350     error_mask = []  # Raise error if encounter one of these
351
352     input_filename = None
353     output_filename = None
354
355 gopts = GlobalOptions
356
357
358 def get_opt():
359     from getopt import getopt, GetoptError
360
361     try:
362         options, arguments = getopt(sys.argv[1:],
363             'hVcCDPH:f:d:p:r:R:b:e:i:t:o:',
364             ['help', 'version', 'host='])
365     except GetoptError:
366         usage(1)
367
368     for option, value in options:
369         if option in ('-h', '--help'):
370             usage()
371         elif option in ('-V', '--version'):
372             version()
373         elif option == '-c':
374             gopts.recode_charset = 1
375         elif option == '-C':
376             gopts.recode_charset = 0
377         elif option in ('-H', '--host'):
378             gopts.host_name = value
379         elif option == '-f':
380             gopts.default_encoding = value
381         elif option == '-d':
382             if value.startswith('*'):
383                 gopts.decode_headers = []
384             gopts.decode_headers.append(value)
385         elif option == '-D':
386             gopts.decode_headers = []
387         elif option == '-p':
388             gopts.decode_header_params.append(value.split(':', 1))
389         elif option == '-P':
390             gopts.decode_header_params = []
391         elif option == '-r':
392             gopts.remove_headers.append(value)
393         elif option == '-R':
394             gopts.remove_header_params.append(value.split(':', 1))
395         elif option == '-t':
396             gopts.totext_mask.append(value)
397         elif option == '-b':
398             gopts.binary_mask.append(value)
399         elif option == '-i':
400             gopts.ignore_mask.append(value)
401         elif option == '-e':
402             gopts.error_mask.append(value)
403         elif option == '-o':
404             gopts.output_filename = value
405         else:
406             usage(1)
407
408     return arguments
409
410
411 if __name__ == "__main__":
412     arguments = get_opt()
413
414     la = len(arguments)
415     if la == 0:
416         gopts.input_filename = '-'
417         infile = sys.stdin
418         if gopts.output_filename:
419             outfile = open(gopts.output_filename, 'w')
420         else:
421             gopts.output_filename = '-'
422             outfile = sys.stdout
423     elif la in (1, 2):
424         if (arguments[0] == '-'):
425             gopts.input_filename = '-'
426             infile = sys.stdin
427         else:
428             gopts.input_filename = arguments[0]
429             infile = open(arguments[0], 'r')
430         if la == 1:
431             if gopts.output_filename:
432                 outfile = open(gopts.output_filename, 'w')
433             else:
434                 gopts.output_filename = '-'
435                 outfile = sys.stdout
436         elif la == 2:
437             if gopts.output_filename:
438                 usage(1, 'Too many output filenames')
439             if (arguments[1] == '-'):
440                 gopts.output_filename = '-'
441                 outfile = sys.stdout
442             else:
443                 gopts.output_filename = arguments[1]
444                 outfile = open(arguments[1], 'w')
445     else:
446         usage(1, 'Too many arguments')
447
448     if (infile is sys.stdin) and sys.stdin.isatty():
449         if (outfile is sys.stdout) and sys.stdout.isatty():
450             usage()
451         usage(1, 'Filtering from console is forbidden')
452
453     if not gopts.host_name:
454         import socket
455         gopts.host_name = socket.gethostname()
456
457     gopts.outfile = outfile
458     output = outfile.write
459
460     try:
461         decode_message(email.message_from_file(infile))
462     finally:
463         infile.close()
464         outfile.close()