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