blob: d0cf0b933345cd07f32281f69d52fcea68adb6cf [file] [log] [blame]
Guido van Rossumbfc39441997-03-25 21:58:08 +00001"""Mailcap file handling. See RFC 1524."""
Guido van Rossum8988fb21995-09-30 16:52:24 +00002
3import os
4import string
Guido van Rossum8988fb21995-09-30 16:52:24 +00005
Skip Montanaro17ab1232001-01-24 06:27:27 +00006__all__ = ["getcaps","findmatch"]
Guido van Rossum8988fb21995-09-30 16:52:24 +00007
8# Part 1: top-level interface.
9
10def getcaps():
Guido van Rossumbfc39441997-03-25 21:58:08 +000011 """Return a dictionary containing the mailcap database.
Tim Peters07e99cb2001-01-14 23:47:14 +000012
Guido van Rossum54f22ed2000-02-04 15:10:34 +000013 The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
14 to a list of dictionaries corresponding to mailcap entries. The list
15 collects all the entries for that MIME type from all available mailcap
16 files. Each dictionary contains key-value pairs for that MIME type,
17 where the viewing command is stored with the key "view".
Guido van Rossumbfc39441997-03-25 21:58:08 +000018
19 """
Guido van Rossum8988fb21995-09-30 16:52:24 +000020 caps = {}
21 for mailcap in listmailcapfiles():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000022 try:
23 fp = open(mailcap, 'r')
24 except:
25 continue
26 morecaps = readmailcapfile(fp)
27 fp.close()
28 for key in morecaps.keys():
29 if not caps.has_key(key):
30 caps[key] = morecaps[key]
31 else:
32 caps[key] = caps[key] + morecaps[key]
Guido van Rossum8988fb21995-09-30 16:52:24 +000033 return caps
34
35def listmailcapfiles():
Guido van Rossumbfc39441997-03-25 21:58:08 +000036 """Return a list of all mailcap files found on the system."""
Guido van Rossum8988fb21995-09-30 16:52:24 +000037 # XXX Actually, this is Unix-specific
38 if os.environ.has_key('MAILCAPS'):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000039 str = os.environ['MAILCAPS']
40 mailcaps = string.splitfields(str, ':')
Guido van Rossum8988fb21995-09-30 16:52:24 +000041 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 if os.environ.has_key('HOME'):
43 home = os.environ['HOME']
44 else:
45 # Don't bother with getpwuid()
46 home = '.' # Last resort
47 mailcaps = [home + '/.mailcap', '/etc/mailcap',
48 '/usr/etc/mailcap', '/usr/local/etc/mailcap']
Guido van Rossum8988fb21995-09-30 16:52:24 +000049 return mailcaps
50
51
52# Part 2: the parser.
53
54def readmailcapfile(fp):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000055 """Read a mailcap file and return a dictionary keyed by MIME type.
56
57 Each MIME type is mapped to an entry consisting of a list of
58 dictionaries; the list will contain more than one such dictionary
59 if a given MIME type appears more than once in the mailcap file.
60 Each dictionary contains key-value pairs for that MIME type, where
61 the viewing command is stored with the key "view".
62 """
Guido van Rossum8988fb21995-09-30 16:52:24 +000063 caps = {}
64 while 1:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000065 line = fp.readline()
66 if not line: break
67 # Ignore comments and blank lines
68 if line[0] == '#' or string.strip(line) == '':
69 continue
70 nextline = line
71 # Join continuation lines
72 while nextline[-2:] == '\\\n':
73 nextline = fp.readline()
74 if not nextline: nextline = '\n'
75 line = line[:-2] + nextline
76 # Parse the line
77 key, fields = parseline(line)
78 if not (key and fields):
79 continue
80 # Normalize the key
81 types = string.splitfields(key, '/')
82 for j in range(len(types)):
83 types[j] = string.strip(types[j])
84 key = string.lower(string.joinfields(types, '/'))
85 # Update the database
86 if caps.has_key(key):
87 caps[key].append(fields)
88 else:
89 caps[key] = [fields]
Guido van Rossum8988fb21995-09-30 16:52:24 +000090 return caps
91
92def parseline(line):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000093 """Parse one entry in a mailcap file and return a dictionary.
94
95 The viewing command is stored as the value with the key "view",
96 and the rest of the fields produce key-value pairs in the dict.
97 """
Guido van Rossum8988fb21995-09-30 16:52:24 +000098 fields = []
99 i, n = 0, len(line)
100 while i < n:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 field, i = parsefield(line, i, n)
102 fields.append(field)
103 i = i+1 # Skip semicolon
Guido van Rossum8988fb21995-09-30 16:52:24 +0000104 if len(fields) < 2:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000105 return None, None
Guido van Rossum8988fb21995-09-30 16:52:24 +0000106 key, view, rest = fields[0], fields[1], fields[2:]
107 fields = {'view': view}
108 for field in rest:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000109 i = string.find(field, '=')
110 if i < 0:
111 fkey = field
112 fvalue = ""
113 else:
114 fkey = string.strip(field[:i])
115 fvalue = string.strip(field[i+1:])
116 if fields.has_key(fkey):
117 # Ignore it
118 pass
119 else:
120 fields[fkey] = fvalue
Guido van Rossum8988fb21995-09-30 16:52:24 +0000121 return key, fields
122
123def parsefield(line, i, n):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000124 """Separate one key-value pair in a mailcap entry."""
Guido van Rossum8988fb21995-09-30 16:52:24 +0000125 start = i
126 while i < n:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000127 c = line[i]
128 if c == ';':
129 break
130 elif c == '\\':
131 i = i+2
132 else:
133 i = i+1
Guido van Rossum8988fb21995-09-30 16:52:24 +0000134 return string.strip(line[start:i]), i
135
136
137# Part 3: using the database.
138
Guido van Rossumbfc39441997-03-25 21:58:08 +0000139def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
140 """Find a match for a mailcap entry.
Tim Peters07e99cb2001-01-14 23:47:14 +0000141
Guido van Rossumbfc39441997-03-25 21:58:08 +0000142 Return a tuple containing the command line, and the mailcap entry
143 used; (None, None) if no match is found. This may invoke the
144 'test' command of several matching entries before deciding which
145 entry to use.
146
147 """
148 entries = lookup(caps, MIMEtype, key)
Tim Peters07e99cb2001-01-14 23:47:14 +0000149 # XXX This code should somehow check for the needsterminal flag.
Guido van Rossum8988fb21995-09-30 16:52:24 +0000150 for e in entries:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 if e.has_key('test'):
152 test = subst(e['test'], filename, plist)
153 if test and os.system(test) != 0:
154 continue
155 command = subst(e[key], MIMEtype, filename, plist)
156 return command, e
Guido van Rossum8988fb21995-09-30 16:52:24 +0000157 return None, None
158
Guido van Rossumbfc39441997-03-25 21:58:08 +0000159def lookup(caps, MIMEtype, key=None):
Guido van Rossum8988fb21995-09-30 16:52:24 +0000160 entries = []
Guido van Rossumbfc39441997-03-25 21:58:08 +0000161 if caps.has_key(MIMEtype):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162 entries = entries + caps[MIMEtype]
Guido van Rossumbfc39441997-03-25 21:58:08 +0000163 MIMEtypes = string.splitfields(MIMEtype, '/')
164 MIMEtype = MIMEtypes[0] + '/*'
165 if caps.has_key(MIMEtype):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 entries = entries + caps[MIMEtype]
Guido van Rossum8988fb21995-09-30 16:52:24 +0000167 if key is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000168 entries = filter(lambda e, key=key: e.has_key(key), entries)
Guido van Rossum8988fb21995-09-30 16:52:24 +0000169 return entries
170
Guido van Rossumbfc39441997-03-25 21:58:08 +0000171def subst(field, MIMEtype, filename, plist=[]):
Guido van Rossum8988fb21995-09-30 16:52:24 +0000172 # XXX Actually, this is Unix-specific
173 res = ''
174 i, n = 0, len(field)
175 while i < n:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000176 c = field[i]; i = i+1
Fred Drake8152d322000-12-12 23:20:45 +0000177 if c != '%':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 if c == '\\':
179 c = field[i:i+1]; i = i+1
180 res = res + c
181 else:
182 c = field[i]; i = i+1
183 if c == '%':
184 res = res + c
185 elif c == 's':
186 res = res + filename
187 elif c == 't':
188 res = res + MIMEtype
189 elif c == '{':
190 start = i
Fred Drake8152d322000-12-12 23:20:45 +0000191 while i < n and field[i] != '}':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 i = i+1
193 name = field[start:i]
194 i = i+1
195 res = res + findparam(name, plist)
196 # XXX To do:
197 # %n == number of parts if type is multipart/*
198 # %F == list of alternating type and filename for parts
199 else:
200 res = res + '%' + c
Guido van Rossum8988fb21995-09-30 16:52:24 +0000201 return res
202
203def findparam(name, plist):
204 name = string.lower(name) + '='
205 n = len(name)
206 for p in plist:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 if string.lower(p[:n]) == name:
208 return p[n:]
Guido van Rossum8988fb21995-09-30 16:52:24 +0000209 return ''
210
211
212# Part 4: test program.
213
214def test():
215 import sys
216 caps = getcaps()
217 if not sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 show(caps)
219 return
Guido van Rossum8988fb21995-09-30 16:52:24 +0000220 for i in range(1, len(sys.argv), 2):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 args = sys.argv[i:i+2]
222 if len(args) < 2:
223 print "usage: mailcap [MIMEtype file] ..."
224 return
225 MIMEtype = args[0]
226 file = args[1]
227 command, e = findmatch(caps, MIMEtype, 'view', file)
228 if not command:
229 print "No viewer found for", type
230 else:
231 print "Executing:", command
232 sts = os.system(command)
233 if sts:
234 print "Exit status:", sts
Guido van Rossum8988fb21995-09-30 16:52:24 +0000235
236def show(caps):
237 print "Mailcap files:"
238 for fn in listmailcapfiles(): print "\t" + fn
239 print
240 if not caps: caps = getcaps()
241 print "Mailcap entries:"
242 print
243 ckeys = caps.keys()
244 ckeys.sort()
245 for type in ckeys:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 print type
247 entries = caps[type]
248 for e in entries:
249 keys = e.keys()
250 keys.sort()
251 for k in keys:
252 print " %-15s" % k, e[k]
253 print
Guido van Rossum8988fb21995-09-30 16:52:24 +0000254
255if __name__ == '__main__':
256 test()