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