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