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