home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Lib / rfc822.py < prev    next >
Text File  |  1994-02-21  |  10KB  |  393 lines

  1. # RFC-822 message manipulation class.
  2. #
  3. # XXX This is only a very rough sketch of a full RFC-822 parser;
  4. # in particular the tokenizing of addresses does not adhere to all the
  5. # quoting rules.
  6. #
  7. # Directions for use:
  8. #
  9. # To create a Message object: first open a file, e.g.:
  10. #   fp = open(file, 'r')
  11. # (or use any other legal way of getting an open file object, e.g. use
  12. # sys.stdin or call os.popen()).
  13. # Then pass the open file object to the Message() constructor:
  14. #   m = Message(fp)
  15. #
  16. # To get the text of a particular header there are several methods:
  17. #   str = m.getheader(name)
  18. #   str = m.getrawheader(name)
  19. # where name is the name of the header, e.g. 'Subject'.
  20. # The difference is that getheader() strips the leading and trailing
  21. # whitespace, while getrawheader() doesn't.  Both functions retain
  22. # embedded whitespace (including newlines) exactly as they are
  23. # specified in the header, and leave the case of the text unchanged.
  24. #
  25. # For addresses and address lists there are functions
  26. #   realname, mailaddress = m.getaddr(name) and
  27. #   list = m.getaddrlist(name)
  28. # where the latter returns a list of (realname, mailaddr) tuples.
  29. #
  30. # There is also a method
  31. #   time = m.getdate(name)
  32. # which parses a Date-like field and returns a time-compatible tuple,
  33. # i.e. a tuple such as returned by time.localtime() or accepted by
  34. # time.mktime().
  35. #
  36. # See the class definition for lower level access methods.
  37. #
  38. # There are also some utility functions here.
  39.  
  40.  
  41. import regex
  42. import string
  43. import time
  44.  
  45.  
  46. class Message:
  47.  
  48.     # Initialize the class instance and read the headers.
  49.     
  50.     def __init__(self, fp):
  51.         self.fp = fp
  52.         #
  53.         try:
  54.             self.startofheaders = self.fp.tell()
  55.         except IOError:
  56.             self.startofheaders = None
  57.         #
  58.         self.readheaders()
  59.         #
  60.         try:
  61.             self.startofbody = self.fp.tell()
  62.         except IOError:
  63.             self.startofbody = None
  64.  
  65.  
  66.     # Rewind the file to the start of the body (if seekable).
  67.  
  68.     def rewindbody(self):
  69.         self.fp.seek(self.startofbody)
  70.  
  71.  
  72.     # Read header lines up to the entirely blank line that
  73.     # terminates them.  The (normally blank) line that ends the
  74.     # headers is skipped, but not included in the returned list.
  75.     # If a non-header line ends the headers, (which is an error),
  76.     # an attempt is made to backspace over it; it is never
  77.     # included in the returned list.
  78.     #
  79.     # The variable self.status is set to the empty string if all
  80.     # went well, otherwise it is an error message.
  81.     # The variable self.headers is a completely uninterpreted list
  82.     # of lines contained in the header (so printing them will
  83.     # reproduce the header exactly as it appears in the file).
  84.  
  85.     def readheaders(self):
  86.         self.headers = list = []
  87.         self.status = ''
  88.         headerseen = 0
  89.         while 1:
  90.             line = self.fp.readline()
  91.             if not line:
  92.                 self.status = 'EOF in headers'
  93.                 break
  94.             if self.islast(line):
  95.                 break
  96.             elif headerseen and line[0] in ' \t':
  97.                 # It's a continuation line.
  98.                 list.append(line)
  99.             elif regex.match('^[!-9;-~]+:', line):
  100.                 # It's a header line.
  101.                 list.append(line)
  102.                 headerseen = 1
  103.             else:
  104.                 # It's not a header line; stop here.
  105.                 if not headerseen:
  106.                     self.status = 'No headers'
  107.                 else:
  108.                     self.status = 'Bad header'
  109.                 # Try to undo the read.
  110.                 try:
  111.                     self.fp.seek(-len(line), 1)
  112.                 except IOError:
  113.                     self.status = \
  114.                         self.status + '; bad seek'
  115.                 break
  116.  
  117.  
  118.     # Method to determine whether a line is a legal end of
  119.     # RFC-822 headers.  You may override this method if your
  120.     # application wants to bend the rules, e.g. to accept lines
  121.     # ending in '\r\n', to strip trailing whitespace, or to
  122.     # recognise MH template separators ('--------'). 
  123.  
  124.     def islast(self, line):
  125.         return line == '\n'
  126.  
  127.  
  128.     # Look through the list of headers and find all lines matching
  129.     # a given header name (and their continuation lines).
  130.     # A list of the lines is returned, without interpretation.
  131.     # If the header does not occur, an empty list is returned.
  132.     # If the header occurs multiple times, all occurrences are
  133.     # returned.  Case is not important in the header name.
  134.  
  135.     def getallmatchingheaders(self, name):
  136.         name = string.lower(name) + ':'
  137.         n = len(name)
  138.         list = []
  139.         hit = 0
  140.         for line in self.headers:
  141.             if string.lower(line[:n]) == name:
  142.                 hit = 1
  143.             elif line[:1] not in string.whitespace:
  144.                 hit = 0
  145.             if hit:
  146.                 list.append(line)
  147.         return list
  148.  
  149.  
  150.     # Similar, but return only the first matching header (and its
  151.     # continuation lines).
  152.  
  153.     def getfirstmatchingheader(self, name):
  154.         name = string.lower(name) + ':'
  155.         n = len(name)
  156.         list = []
  157.         hit = 0
  158.         for line in self.headers:
  159.             if string.lower(line[:n]) == name:
  160.                 hit = 1
  161.             elif line[:1] not in string.whitespace:
  162.                 if hit:
  163.                     break
  164.             if hit:
  165.                 list.append(line)
  166.         return list
  167.  
  168.  
  169.     # A higher-level interface to getfirstmatchingheader().
  170.     # Return a string containing the literal text of the header
  171.     # but with the keyword stripped.  All leading, trailing and
  172.     # embedded whitespace is kept in the string, however.
  173.     # Return None if the header does not occur.
  174.  
  175.     def getrawheader(self, name):
  176.         list = self.getfirstmatchingheader(name)
  177.         if not list:
  178.             return None
  179.         list[0] = list[0][len(name) + 1:]
  180.         return string.joinfields(list, '')
  181.  
  182.  
  183.     # Going one step further: also strip leading and trailing
  184.     # whitespace.
  185.  
  186.     def getheader(self, name):
  187.         text = self.getrawheader(name)
  188.         if text == None:
  189.             return None
  190.         return string.strip(text)
  191.  
  192.  
  193.     # Retrieve a single address from a header as a tuple, e.g.
  194.     # ('Guido van Rossum', 'guido@cwi.nl').
  195.  
  196.     def getaddr(self, name):
  197.         data = self.getheader(name)
  198.         if not data:
  199.             return None, None
  200.         return parseaddr(data)
  201.  
  202.     # Retrieve a list of addresses from a header, where each
  203.     # address is a tuple as returned by getaddr().
  204.  
  205.     def getaddrlist(self, name):
  206.         # XXX This function is not really correct.  The split
  207.         # on ',' might fail in the case of commas within
  208.         # quoted strings.
  209.         data = self.getheader(name)
  210.         if not data:
  211.             return []
  212.         data = string.splitfields(data, ',')
  213.         for i in range(len(data)):
  214.             data[i] = parseaddr(data[i])
  215.         return data
  216.  
  217.     # Retrieve a date field from a header as a tuple compatible
  218.     # with time.mktime().
  219.  
  220.     def getdate(self, name):
  221.         data = self.getheader(name)
  222.         if not data:
  223.             return None
  224.         return parsedate(data)
  225.  
  226.  
  227.     # Access as a dictionary (only finds first header of each type):
  228.  
  229.     def __len__(self):
  230.         types = {}
  231.         for line in self.headers:
  232.             if line[0] in string.whitespace: continue
  233.             i = string.find(line, ':')
  234.             if i > 0:
  235.                 name = string.lower(line[:i])
  236.                 types[name] = None
  237.         return len(types)
  238.  
  239.     def __getitem__(self, name):
  240.         value = self.getheader(name)
  241.         if value is None: raise KeyError, name
  242.         return value
  243.  
  244.     def has_key(self, name):
  245.         value = self.getheader(name)
  246.         return value is not None
  247.  
  248.     def keys(self):
  249.         types = {}
  250.         for line in self.headers:
  251.             if line[0] in string.whitespace: continue
  252.             i = string.find(line, ':')
  253.             if i > 0:
  254.                 name = line[:i]
  255.                 key = string.lower(name)
  256.                 types[key] = name
  257.         return types.values()
  258.  
  259.     def values(self):
  260.         values = []
  261.         for name in self.keys():
  262.             values.append(self[name])
  263.         return values
  264.  
  265.     def items(self):
  266.         items = []
  267.         for name in self.keys():
  268.             items.append(name, self[name])
  269.         return items
  270.  
  271.  
  272.  
  273. # Utility functions
  274. # -----------------
  275.  
  276. # XXX Should fix these to be really conformant.
  277. # XXX The inverses of the parse functions may also be useful.
  278.  
  279.  
  280. # Remove quotes from a string.
  281.  
  282. def unquote(str):
  283.     if len(str) > 1:
  284.         if str[0] == '"' and str[-1:] == '"':
  285.             return str[1:-1]
  286.         if str[0] == '<' and str[-1:] == '>':
  287.             return str[1:-1]
  288.     return str
  289.  
  290.  
  291. # Parse an address into (name, address) tuple
  292.  
  293. def parseaddr(address):
  294.     # This is probably not perfect
  295.     address = string.strip(address)
  296.     # Case 1: part of the address is in <xx@xx> form.
  297.     pos = regex.search('<.*>', address)
  298.     if pos >= 0:
  299.         name = address[:pos]
  300.         address = address[pos:]
  301.         length = regex.match('<.*>', address)
  302.         name = name + address[length:]
  303.         address = address[:length]
  304.     else:
  305.         # Case 2: part of the address is in (comment) form
  306.         pos = regex.search('(.*)', address)
  307.         if pos >= 0:
  308.             name = address[pos:]
  309.             address = address[:pos]
  310.             length = regex.match('(.*)', name)
  311.             address = address + name[length:]
  312.             name = name[:length]
  313.         else:
  314.             # Case 3: neither. Only an address
  315.             name = ''
  316.     name = string.strip(name)
  317.     address = string.strip(address)
  318.     if address and address[0] == '<' and address[-1] == '>':
  319.         address = address[1:-1]
  320.     if name and name[0] == '(' and name[-1] == ')':
  321.         name = name[1:-1]
  322.     return name, address
  323.  
  324.  
  325. # Parse a date field
  326.  
  327. _monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
  328.       'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  329.  
  330. def parsedate(data):
  331.     # XXX This completely ignores timezone matters at the moment...
  332.     data = string.split(data)
  333.     if data[0][-1] == ',':
  334.         # There's a dayname here. Skip it
  335.         del data[0]
  336.     if len(data) < 5:
  337.         return None
  338.     data = data[:5]
  339.     [dd, mm, yy, tm, tz] = data
  340.     if not mm in _monthnames:
  341.         return None
  342.     mm = _monthnames.index(mm)+1
  343.     tm = string.splitfields(tm, ':')
  344.     if len(tm) == 2:
  345.         [thh, tmm] = tm
  346.         tss = '0'
  347.     else:
  348.         [thh, tmm, tss] = tm
  349.     try:
  350.         yy = string.atoi(yy)
  351.         dd = string.atoi(dd)
  352.         thh = string.atoi(thh)
  353.         tmm = string.atoi(tmm)
  354.         tss = string.atoi(tss)
  355.     except string.atoi_error:
  356.         return None
  357.     tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0)
  358.     return tuple
  359.  
  360.  
  361. # When used as script, run a small test program.
  362. # The first command line argument must be a filename containing one
  363. # message in RFC-822 format.
  364.  
  365. if __name__ == '__main__':
  366.     import sys
  367.     file = '/ufs/guido/Mail/drafts/,1'
  368.     if sys.argv[1:]: file = sys.argv[1]
  369.     f = open(file, 'r')
  370.     m = Message(f)
  371.     print 'From:', m.getaddr('from')
  372.     print 'To:', m.getaddrlist('to')
  373.     print 'Subject:', m.getheader('subject')
  374.     print 'Date:', m.getheader('date')
  375.     date = m.getdate('date')
  376.     if date:
  377.         print 'ParsedDate:', time.asctime(date)
  378.     else:
  379.         print 'ParsedDate:', None
  380.     m.rewindbody()
  381.     n = 0
  382.     while f.readline():
  383.         n = n + 1
  384.     print 'Lines:', n
  385.     print '-'*70
  386.     print 'len =', len(m)
  387.     if m.has_key('Date'): print 'Date =', m['Date']
  388.     if m.has_key('X-Nonsense'): pass
  389.     print 'keys =', m.keys()
  390.     print 'values =', m.values()
  391.     print 'items =', m.items()
  392.     
  393.