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