1 | n/a | """Mailcap file handling. See RFC 1524.""" |
---|
2 | n/a | |
---|
3 | n/a | import os |
---|
4 | n/a | import warnings |
---|
5 | n/a | |
---|
6 | n/a | __all__ = ["getcaps","findmatch"] |
---|
7 | n/a | |
---|
8 | n/a | |
---|
9 | n/a | def lineno_sort_key(entry): |
---|
10 | n/a | # Sort in ascending order, with unspecified entries at the end |
---|
11 | n/a | if 'lineno' in entry: |
---|
12 | n/a | return 0, entry['lineno'] |
---|
13 | n/a | else: |
---|
14 | n/a | return 1, 0 |
---|
15 | n/a | |
---|
16 | n/a | |
---|
17 | n/a | # Part 1: top-level interface. |
---|
18 | n/a | |
---|
19 | n/a | def getcaps(): |
---|
20 | n/a | """Return a dictionary containing the mailcap database. |
---|
21 | n/a | |
---|
22 | n/a | The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') |
---|
23 | n/a | to a list of dictionaries corresponding to mailcap entries. The list |
---|
24 | n/a | collects all the entries for that MIME type from all available mailcap |
---|
25 | n/a | files. Each dictionary contains key-value pairs for that MIME type, |
---|
26 | n/a | where the viewing command is stored with the key "view". |
---|
27 | n/a | |
---|
28 | n/a | """ |
---|
29 | n/a | caps = {} |
---|
30 | n/a | lineno = 0 |
---|
31 | n/a | for mailcap in listmailcapfiles(): |
---|
32 | n/a | try: |
---|
33 | n/a | fp = open(mailcap, 'r') |
---|
34 | n/a | except OSError: |
---|
35 | n/a | continue |
---|
36 | n/a | with fp: |
---|
37 | n/a | morecaps, lineno = _readmailcapfile(fp, lineno) |
---|
38 | n/a | for key, value in morecaps.items(): |
---|
39 | n/a | if not key in caps: |
---|
40 | n/a | caps[key] = value |
---|
41 | n/a | else: |
---|
42 | n/a | caps[key] = caps[key] + value |
---|
43 | n/a | return caps |
---|
44 | n/a | |
---|
45 | n/a | def listmailcapfiles(): |
---|
46 | n/a | """Return a list of all mailcap files found on the system.""" |
---|
47 | n/a | # This is mostly a Unix thing, but we use the OS path separator anyway |
---|
48 | n/a | if 'MAILCAPS' in os.environ: |
---|
49 | n/a | pathstr = os.environ['MAILCAPS'] |
---|
50 | n/a | mailcaps = pathstr.split(os.pathsep) |
---|
51 | n/a | else: |
---|
52 | n/a | if 'HOME' in os.environ: |
---|
53 | n/a | home = os.environ['HOME'] |
---|
54 | n/a | else: |
---|
55 | n/a | # Don't bother with getpwuid() |
---|
56 | n/a | home = '.' # Last resort |
---|
57 | n/a | mailcaps = [home + '/.mailcap', '/etc/mailcap', |
---|
58 | n/a | '/usr/etc/mailcap', '/usr/local/etc/mailcap'] |
---|
59 | n/a | return mailcaps |
---|
60 | n/a | |
---|
61 | n/a | |
---|
62 | n/a | # Part 2: the parser. |
---|
63 | n/a | def readmailcapfile(fp): |
---|
64 | n/a | """Read a mailcap file and return a dictionary keyed by MIME type.""" |
---|
65 | n/a | warnings.warn('readmailcapfile is deprecated, use getcaps instead', |
---|
66 | n/a | DeprecationWarning, 2) |
---|
67 | n/a | caps, _ = _readmailcapfile(fp, None) |
---|
68 | n/a | return caps |
---|
69 | n/a | |
---|
70 | n/a | |
---|
71 | n/a | def _readmailcapfile(fp, lineno): |
---|
72 | n/a | """Read a mailcap file and return a dictionary keyed by MIME type. |
---|
73 | n/a | |
---|
74 | n/a | Each MIME type is mapped to an entry consisting of a list of |
---|
75 | n/a | dictionaries; the list will contain more than one such dictionary |
---|
76 | n/a | if a given MIME type appears more than once in the mailcap file. |
---|
77 | n/a | Each dictionary contains key-value pairs for that MIME type, where |
---|
78 | n/a | the viewing command is stored with the key "view". |
---|
79 | n/a | """ |
---|
80 | n/a | caps = {} |
---|
81 | n/a | while 1: |
---|
82 | n/a | line = fp.readline() |
---|
83 | n/a | if not line: break |
---|
84 | n/a | # Ignore comments and blank lines |
---|
85 | n/a | if line[0] == '#' or line.strip() == '': |
---|
86 | n/a | continue |
---|
87 | n/a | nextline = line |
---|
88 | n/a | # Join continuation lines |
---|
89 | n/a | while nextline[-2:] == '\\\n': |
---|
90 | n/a | nextline = fp.readline() |
---|
91 | n/a | if not nextline: nextline = '\n' |
---|
92 | n/a | line = line[:-2] + nextline |
---|
93 | n/a | # Parse the line |
---|
94 | n/a | key, fields = parseline(line) |
---|
95 | n/a | if not (key and fields): |
---|
96 | n/a | continue |
---|
97 | n/a | if lineno is not None: |
---|
98 | n/a | fields['lineno'] = lineno |
---|
99 | n/a | lineno += 1 |
---|
100 | n/a | # Normalize the key |
---|
101 | n/a | types = key.split('/') |
---|
102 | n/a | for j in range(len(types)): |
---|
103 | n/a | types[j] = types[j].strip() |
---|
104 | n/a | key = '/'.join(types).lower() |
---|
105 | n/a | # Update the database |
---|
106 | n/a | if key in caps: |
---|
107 | n/a | caps[key].append(fields) |
---|
108 | n/a | else: |
---|
109 | n/a | caps[key] = [fields] |
---|
110 | n/a | return caps, lineno |
---|
111 | n/a | |
---|
112 | n/a | def parseline(line): |
---|
113 | n/a | """Parse one entry in a mailcap file and return a dictionary. |
---|
114 | n/a | |
---|
115 | n/a | The viewing command is stored as the value with the key "view", |
---|
116 | n/a | and the rest of the fields produce key-value pairs in the dict. |
---|
117 | n/a | """ |
---|
118 | n/a | fields = [] |
---|
119 | n/a | i, n = 0, len(line) |
---|
120 | n/a | while i < n: |
---|
121 | n/a | field, i = parsefield(line, i, n) |
---|
122 | n/a | fields.append(field) |
---|
123 | n/a | i = i+1 # Skip semicolon |
---|
124 | n/a | if len(fields) < 2: |
---|
125 | n/a | return None, None |
---|
126 | n/a | key, view, rest = fields[0], fields[1], fields[2:] |
---|
127 | n/a | fields = {'view': view} |
---|
128 | n/a | for field in rest: |
---|
129 | n/a | i = field.find('=') |
---|
130 | n/a | if i < 0: |
---|
131 | n/a | fkey = field |
---|
132 | n/a | fvalue = "" |
---|
133 | n/a | else: |
---|
134 | n/a | fkey = field[:i].strip() |
---|
135 | n/a | fvalue = field[i+1:].strip() |
---|
136 | n/a | if fkey in fields: |
---|
137 | n/a | # Ignore it |
---|
138 | n/a | pass |
---|
139 | n/a | else: |
---|
140 | n/a | fields[fkey] = fvalue |
---|
141 | n/a | return key, fields |
---|
142 | n/a | |
---|
143 | n/a | def parsefield(line, i, n): |
---|
144 | n/a | """Separate one key-value pair in a mailcap entry.""" |
---|
145 | n/a | start = i |
---|
146 | n/a | while i < n: |
---|
147 | n/a | c = line[i] |
---|
148 | n/a | if c == ';': |
---|
149 | n/a | break |
---|
150 | n/a | elif c == '\\': |
---|
151 | n/a | i = i+2 |
---|
152 | n/a | else: |
---|
153 | n/a | i = i+1 |
---|
154 | n/a | return line[start:i].strip(), i |
---|
155 | n/a | |
---|
156 | n/a | |
---|
157 | n/a | # Part 3: using the database. |
---|
158 | n/a | |
---|
159 | n/a | def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]): |
---|
160 | n/a | """Find a match for a mailcap entry. |
---|
161 | n/a | |
---|
162 | n/a | Return a tuple containing the command line, and the mailcap entry |
---|
163 | n/a | used; (None, None) if no match is found. This may invoke the |
---|
164 | n/a | 'test' command of several matching entries before deciding which |
---|
165 | n/a | entry to use. |
---|
166 | n/a | |
---|
167 | n/a | """ |
---|
168 | n/a | entries = lookup(caps, MIMEtype, key) |
---|
169 | n/a | # XXX This code should somehow check for the needsterminal flag. |
---|
170 | n/a | for e in entries: |
---|
171 | n/a | if 'test' in e: |
---|
172 | n/a | test = subst(e['test'], filename, plist) |
---|
173 | n/a | if test and os.system(test) != 0: |
---|
174 | n/a | continue |
---|
175 | n/a | command = subst(e[key], MIMEtype, filename, plist) |
---|
176 | n/a | return command, e |
---|
177 | n/a | return None, None |
---|
178 | n/a | |
---|
179 | n/a | def lookup(caps, MIMEtype, key=None): |
---|
180 | n/a | entries = [] |
---|
181 | n/a | if MIMEtype in caps: |
---|
182 | n/a | entries = entries + caps[MIMEtype] |
---|
183 | n/a | MIMEtypes = MIMEtype.split('/') |
---|
184 | n/a | MIMEtype = MIMEtypes[0] + '/*' |
---|
185 | n/a | if MIMEtype in caps: |
---|
186 | n/a | entries = entries + caps[MIMEtype] |
---|
187 | n/a | if key is not None: |
---|
188 | n/a | entries = [e for e in entries if key in e] |
---|
189 | n/a | entries = sorted(entries, key=lineno_sort_key) |
---|
190 | n/a | return entries |
---|
191 | n/a | |
---|
192 | n/a | def subst(field, MIMEtype, filename, plist=[]): |
---|
193 | n/a | # XXX Actually, this is Unix-specific |
---|
194 | n/a | res = '' |
---|
195 | n/a | i, n = 0, len(field) |
---|
196 | n/a | while i < n: |
---|
197 | n/a | c = field[i]; i = i+1 |
---|
198 | n/a | if c != '%': |
---|
199 | n/a | if c == '\\': |
---|
200 | n/a | c = field[i:i+1]; i = i+1 |
---|
201 | n/a | res = res + c |
---|
202 | n/a | else: |
---|
203 | n/a | c = field[i]; i = i+1 |
---|
204 | n/a | if c == '%': |
---|
205 | n/a | res = res + c |
---|
206 | n/a | elif c == 's': |
---|
207 | n/a | res = res + filename |
---|
208 | n/a | elif c == 't': |
---|
209 | n/a | res = res + MIMEtype |
---|
210 | n/a | elif c == '{': |
---|
211 | n/a | start = i |
---|
212 | n/a | while i < n and field[i] != '}': |
---|
213 | n/a | i = i+1 |
---|
214 | n/a | name = field[start:i] |
---|
215 | n/a | i = i+1 |
---|
216 | n/a | res = res + findparam(name, plist) |
---|
217 | n/a | # XXX To do: |
---|
218 | n/a | # %n == number of parts if type is multipart/* |
---|
219 | n/a | # %F == list of alternating type and filename for parts |
---|
220 | n/a | else: |
---|
221 | n/a | res = res + '%' + c |
---|
222 | n/a | return res |
---|
223 | n/a | |
---|
224 | n/a | def findparam(name, plist): |
---|
225 | n/a | name = name.lower() + '=' |
---|
226 | n/a | n = len(name) |
---|
227 | n/a | for p in plist: |
---|
228 | n/a | if p[:n].lower() == name: |
---|
229 | n/a | return p[n:] |
---|
230 | n/a | return '' |
---|
231 | n/a | |
---|
232 | n/a | |
---|
233 | n/a | # Part 4: test program. |
---|
234 | n/a | |
---|
235 | n/a | def test(): |
---|
236 | n/a | import sys |
---|
237 | n/a | caps = getcaps() |
---|
238 | n/a | if not sys.argv[1:]: |
---|
239 | n/a | show(caps) |
---|
240 | n/a | return |
---|
241 | n/a | for i in range(1, len(sys.argv), 2): |
---|
242 | n/a | args = sys.argv[i:i+2] |
---|
243 | n/a | if len(args) < 2: |
---|
244 | n/a | print("usage: mailcap [MIMEtype file] ...") |
---|
245 | n/a | return |
---|
246 | n/a | MIMEtype = args[0] |
---|
247 | n/a | file = args[1] |
---|
248 | n/a | command, e = findmatch(caps, MIMEtype, 'view', file) |
---|
249 | n/a | if not command: |
---|
250 | n/a | print("No viewer found for", type) |
---|
251 | n/a | else: |
---|
252 | n/a | print("Executing:", command) |
---|
253 | n/a | sts = os.system(command) |
---|
254 | n/a | if sts: |
---|
255 | n/a | print("Exit status:", sts) |
---|
256 | n/a | |
---|
257 | n/a | def show(caps): |
---|
258 | n/a | print("Mailcap files:") |
---|
259 | n/a | for fn in listmailcapfiles(): print("\t" + fn) |
---|
260 | n/a | print() |
---|
261 | n/a | if not caps: caps = getcaps() |
---|
262 | n/a | print("Mailcap entries:") |
---|
263 | n/a | print() |
---|
264 | n/a | ckeys = sorted(caps) |
---|
265 | n/a | for type in ckeys: |
---|
266 | n/a | print(type) |
---|
267 | n/a | entries = caps[type] |
---|
268 | n/a | for e in entries: |
---|
269 | n/a | keys = sorted(e) |
---|
270 | n/a | for k in keys: |
---|
271 | n/a | print(" %-15s" % k, e[k]) |
---|
272 | n/a | print() |
---|
273 | n/a | |
---|
274 | n/a | if __name__ == '__main__': |
---|
275 | n/a | test() |
---|