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