+++ /dev/null
-"""Mailcap file handling. See RFC 1524."""\r
-\r
-import os\r
-\r
-__all__ = ["getcaps","findmatch"]\r
-\r
-# Part 1: top-level interface.\r
-\r
-def getcaps():\r
- """Return a dictionary containing the mailcap database.\r
-\r
- The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')\r
- to a list of dictionaries corresponding to mailcap entries. The list\r
- collects all the entries for that MIME type from all available mailcap\r
- files. Each dictionary contains key-value pairs for that MIME type,\r
- where the viewing command is stored with the key "view".\r
-\r
- """\r
- caps = {}\r
- for mailcap in listmailcapfiles():\r
- try:\r
- fp = open(mailcap, 'r')\r
- except IOError:\r
- continue\r
- morecaps = readmailcapfile(fp)\r
- fp.close()\r
- for key, value in morecaps.iteritems():\r
- if not key in caps:\r
- caps[key] = value\r
- else:\r
- caps[key] = caps[key] + value\r
- return caps\r
-\r
-def listmailcapfiles():\r
- """Return a list of all mailcap files found on the system."""\r
- # XXX Actually, this is Unix-specific\r
- if 'MAILCAPS' in os.environ:\r
- str = os.environ['MAILCAPS']\r
- mailcaps = str.split(':')\r
- else:\r
- if 'HOME' in os.environ:\r
- home = os.environ['HOME']\r
- else:\r
- # Don't bother with getpwuid()\r
- home = '.' # Last resort\r
- mailcaps = [home + '/.mailcap', '/etc/mailcap',\r
- '/usr/etc/mailcap', '/usr/local/etc/mailcap']\r
- return mailcaps\r
-\r
-\r
-# Part 2: the parser.\r
-\r
-def readmailcapfile(fp):\r
- """Read a mailcap file and return a dictionary keyed by MIME type.\r
-\r
- Each MIME type is mapped to an entry consisting of a list of\r
- dictionaries; the list will contain more than one such dictionary\r
- if a given MIME type appears more than once in the mailcap file.\r
- Each dictionary contains key-value pairs for that MIME type, where\r
- the viewing command is stored with the key "view".\r
- """\r
- caps = {}\r
- while 1:\r
- line = fp.readline()\r
- if not line: break\r
- # Ignore comments and blank lines\r
- if line[0] == '#' or line.strip() == '':\r
- continue\r
- nextline = line\r
- # Join continuation lines\r
- while nextline[-2:] == '\\\n':\r
- nextline = fp.readline()\r
- if not nextline: nextline = '\n'\r
- line = line[:-2] + nextline\r
- # Parse the line\r
- key, fields = parseline(line)\r
- if not (key and fields):\r
- continue\r
- # Normalize the key\r
- types = key.split('/')\r
- for j in range(len(types)):\r
- types[j] = types[j].strip()\r
- key = '/'.join(types).lower()\r
- # Update the database\r
- if key in caps:\r
- caps[key].append(fields)\r
- else:\r
- caps[key] = [fields]\r
- return caps\r
-\r
-def parseline(line):\r
- """Parse one entry in a mailcap file and return a dictionary.\r
-\r
- The viewing command is stored as the value with the key "view",\r
- and the rest of the fields produce key-value pairs in the dict.\r
- """\r
- fields = []\r
- i, n = 0, len(line)\r
- while i < n:\r
- field, i = parsefield(line, i, n)\r
- fields.append(field)\r
- i = i+1 # Skip semicolon\r
- if len(fields) < 2:\r
- return None, None\r
- key, view, rest = fields[0], fields[1], fields[2:]\r
- fields = {'view': view}\r
- for field in rest:\r
- i = field.find('=')\r
- if i < 0:\r
- fkey = field\r
- fvalue = ""\r
- else:\r
- fkey = field[:i].strip()\r
- fvalue = field[i+1:].strip()\r
- if fkey in fields:\r
- # Ignore it\r
- pass\r
- else:\r
- fields[fkey] = fvalue\r
- return key, fields\r
-\r
-def parsefield(line, i, n):\r
- """Separate one key-value pair in a mailcap entry."""\r
- start = i\r
- while i < n:\r
- c = line[i]\r
- if c == ';':\r
- break\r
- elif c == '\\':\r
- i = i+2\r
- else:\r
- i = i+1\r
- return line[start:i].strip(), i\r
-\r
-\r
-# Part 3: using the database.\r
-\r
-def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):\r
- """Find a match for a mailcap entry.\r
-\r
- Return a tuple containing the command line, and the mailcap entry\r
- used; (None, None) if no match is found. This may invoke the\r
- 'test' command of several matching entries before deciding which\r
- entry to use.\r
-\r
- """\r
- entries = lookup(caps, MIMEtype, key)\r
- # XXX This code should somehow check for the needsterminal flag.\r
- for e in entries:\r
- if 'test' in e:\r
- test = subst(e['test'], filename, plist)\r
- if test and os.system(test) != 0:\r
- continue\r
- command = subst(e[key], MIMEtype, filename, plist)\r
- return command, e\r
- return None, None\r
-\r
-def lookup(caps, MIMEtype, key=None):\r
- entries = []\r
- if MIMEtype in caps:\r
- entries = entries + caps[MIMEtype]\r
- MIMEtypes = MIMEtype.split('/')\r
- MIMEtype = MIMEtypes[0] + '/*'\r
- if MIMEtype in caps:\r
- entries = entries + caps[MIMEtype]\r
- if key is not None:\r
- entries = filter(lambda e, key=key: key in e, entries)\r
- return entries\r
-\r
-def subst(field, MIMEtype, filename, plist=[]):\r
- # XXX Actually, this is Unix-specific\r
- res = ''\r
- i, n = 0, len(field)\r
- while i < n:\r
- c = field[i]; i = i+1\r
- if c != '%':\r
- if c == '\\':\r
- c = field[i:i+1]; i = i+1\r
- res = res + c\r
- else:\r
- c = field[i]; i = i+1\r
- if c == '%':\r
- res = res + c\r
- elif c == 's':\r
- res = res + filename\r
- elif c == 't':\r
- res = res + MIMEtype\r
- elif c == '{':\r
- start = i\r
- while i < n and field[i] != '}':\r
- i = i+1\r
- name = field[start:i]\r
- i = i+1\r
- res = res + findparam(name, plist)\r
- # XXX To do:\r
- # %n == number of parts if type is multipart/*\r
- # %F == list of alternating type and filename for parts\r
- else:\r
- res = res + '%' + c\r
- return res\r
-\r
-def findparam(name, plist):\r
- name = name.lower() + '='\r
- n = len(name)\r
- for p in plist:\r
- if p[:n].lower() == name:\r
- return p[n:]\r
- return ''\r
-\r
-\r
-# Part 4: test program.\r
-\r
-def test():\r
- import sys\r
- caps = getcaps()\r
- if not sys.argv[1:]:\r
- show(caps)\r
- return\r
- for i in range(1, len(sys.argv), 2):\r
- args = sys.argv[i:i+2]\r
- if len(args) < 2:\r
- print "usage: mailcap [MIMEtype file] ..."\r
- return\r
- MIMEtype = args[0]\r
- file = args[1]\r
- command, e = findmatch(caps, MIMEtype, 'view', file)\r
- if not command:\r
- print "No viewer found for", type\r
- else:\r
- print "Executing:", command\r
- sts = os.system(command)\r
- if sts:\r
- print "Exit status:", sts\r
-\r
-def show(caps):\r
- print "Mailcap files:"\r
- for fn in listmailcapfiles(): print "\t" + fn\r
- print\r
- if not caps: caps = getcaps()\r
- print "Mailcap entries:"\r
- print\r
- ckeys = caps.keys()\r
- ckeys.sort()\r
- for type in ckeys:\r
- print type\r
- entries = caps[type]\r
- for e in entries:\r
- keys = e.keys()\r
- keys.sort()\r
- for k in keys:\r
- print " %-15s" % k, e[k]\r
- print\r
-\r
-if __name__ == '__main__':\r
- test()\r