home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / nntplib.py < prev    next >
Text File  |  1997-10-22  |  13KB  |  478 lines

  1. # An NNTP client class.  Based on RFC 977: Network News Transfer
  2. # Protocol, by Brian Kantor and Phil Lapsley.
  3.  
  4.  
  5. # Example:
  6. #
  7. # >>> from nntplib import NNTP
  8. # >>> s = NNTP('news')
  9. # >>> resp, count, first, last, name = s.group('comp.lang.python')
  10. # >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
  11. # Group comp.lang.python has 51 articles, range 5770 to 5821
  12. # >>> resp, subs = s.xhdr('subject', first + '-' + last)
  13. # >>> resp = s.quit()
  14. # >>>
  15. #
  16. # Here 'resp' is the server response line.
  17. # Error responses are turned into exceptions.
  18. #
  19. # To post an article from a file:
  20. # >>> f = open(filename, 'r') # file containing article, including header
  21. # >>> resp = s.post(f)
  22. # >>>
  23. #
  24. # For descriptions of all methods, read the comments in the code below.
  25. # Note that all arguments and return values representing article numbers
  26. # are strings, not numbers, since they are rarely used for calculations.
  27.  
  28. # (xover, xgtitle, xpath, date methods by Kevan Heydon)
  29.  
  30.  
  31. # Imports
  32. import re
  33. import socket
  34. import string
  35.  
  36.  
  37. # Exception raised when an error or invalid response is received
  38.  
  39. error_reply = 'nntplib.error_reply'    # unexpected [123]xx reply
  40. error_temp = 'nntplib.error_temp'    # 4xx errors
  41. error_perm = 'nntplib.error_perm'    # 5xx errors
  42. error_proto = 'nntplib.error_proto'    # response does not begin with [1-5]
  43. error_data = 'nntplib.error_data'    # error in response data
  44.  
  45.  
  46. # Standard port used by NNTP servers
  47. NNTP_PORT = 119
  48.  
  49.  
  50. # Response numbers that are followed by additional text (e.g. article)
  51. LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282']
  52.  
  53.  
  54. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  55. CRLF = '\r\n'
  56.  
  57.  
  58. # The class itself
  59.  
  60. class NNTP:
  61.  
  62.     # Initialize an instance.  Arguments:
  63.     # - host: hostname to connect to
  64.     # - port: port to connect to (default the standard NNTP port)
  65.  
  66.     def __init__(self, host, port = NNTP_PORT, user=None, password=None):
  67.         self.host = host
  68.         self.port = port
  69.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  70.         self.sock.connect(self.host, self.port)
  71.         self.file = self.sock.makefile('rb')
  72.         self.debugging = 0
  73.         self.welcome = self.getresp()
  74.         if user:
  75.             resp = self.shortcmd('authinfo user '+user)
  76.             if resp[:3] == '381':
  77.             if not password:
  78.                 raise error_reply, resp
  79.             else:
  80.                 resp = self.shortcmd('authinfo pass '+password)
  81.                 if resp[:3] != '281':
  82.                 raise error_perm, resp
  83.  
  84.     # Get the welcome message from the server
  85.     # (this is read and squirreled away by __init__()).
  86.     # If the response code is 200, posting is allowed;
  87.     # if it 201, posting is not allowed
  88.  
  89.     def getwelcome(self):
  90.         if self.debugging: print '*welcome*', `self.welcome`
  91.         return self.welcome
  92.  
  93.     # Set the debugging level.  Argument level means:
  94.     # 0: no debugging output (default)
  95.     # 1: print commands and responses but not body text etc.
  96.     # 2: also print raw lines read and sent before stripping CR/LF
  97.  
  98.     def set_debuglevel(self, level):
  99.         self.debugging = level
  100.     debug = set_debuglevel
  101.  
  102.     # Internal: send one line to the server, appending CRLF
  103.     def putline(self, line):
  104.         line = line + CRLF
  105.         if self.debugging > 1: print '*put*', `line`
  106.         self.sock.send(line)
  107.  
  108.     # Internal: send one command to the server (through putline())
  109.     def putcmd(self, line):
  110.         if self.debugging: print '*cmd*', `line`
  111.         self.putline(line)
  112.  
  113.     # Internal: return one line from the server, stripping CRLF.
  114.     # Raise EOFError if the connection is closed
  115.     def getline(self):
  116.         line = self.file.readline()
  117.         if self.debugging > 1:
  118.             print '*get*', `line`
  119.         if not line: raise EOFError
  120.         if line[-2:] == CRLF: line = line[:-2]
  121.         elif line[-1:] in CRLF: line = line[:-1]
  122.         return line
  123.  
  124.     # Internal: get a response from the server.
  125.     # Raise various errors if the response indicates an error
  126.     def getresp(self):
  127.         resp = self.getline()
  128.         if self.debugging: print '*resp*', `resp`
  129.         c = resp[:1]
  130.         if c == '4':
  131.             raise error_temp, resp
  132.         if c == '5':
  133.             raise error_perm, resp
  134.         if c not in '123':
  135.             raise error_proto, resp
  136.         return resp
  137.  
  138.     # Internal: get a response plus following text from the server.
  139.     # Raise various errors if the response indicates an error
  140.     def getlongresp(self):
  141.         resp = self.getresp()
  142.         if resp[:3] not in LONGRESP:
  143.             raise error_reply, resp
  144.         list = []
  145.         while 1:
  146.             line = self.getline()
  147.             if line == '.':
  148.                 break
  149.             if line[:2] == '..':
  150.                 line = line[1:]
  151.             list.append(line)
  152.         return resp, list
  153.  
  154.     # Internal: send a command and get the response
  155.     def shortcmd(self, line):
  156.         self.putcmd(line)
  157.         return self.getresp()
  158.  
  159.     # Internal: send a command and get the response plus following text
  160.     def longcmd(self, line):
  161.         self.putcmd(line)
  162.         return self.getlongresp()
  163.  
  164.     # Process a NEWGROUPS command.  Arguments:
  165.     # - date: string 'yymmdd' indicating the date
  166.     # - time: string 'hhmmss' indicating the time
  167.     # Return:
  168.     # - resp: server response if succesful
  169.     # - list: list of newsgroup names
  170.  
  171.     def newgroups(self, date, time):
  172.         return self.longcmd('NEWGROUPS ' + date + ' ' + time)
  173.  
  174.     # Process a NEWNEWS command.  Arguments:
  175.     # - group: group name or '*'
  176.     # - date: string 'yymmdd' indicating the date
  177.     # - time: string 'hhmmss' indicating the time
  178.     # Return:
  179.     # - resp: server response if succesful
  180.     # - list: list of article ids
  181.  
  182.     def newnews(self, group, date, time):
  183.         cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time
  184.         return self.longcmd(cmd)
  185.  
  186.     # Process a LIST command.  Return:
  187.     # - resp: server response if succesful
  188.     # - list: list of (group, last, first, flag) (strings)
  189.  
  190.     def list(self):
  191.         resp, list = self.longcmd('LIST')
  192.         for i in range(len(list)):
  193.             # Parse lines into "group last first flag"
  194.             list[i] = tuple(string.split(list[i]))
  195.         return resp, list
  196.  
  197.     # Process a GROUP command.  Argument:
  198.     # - group: the group name
  199.     # Returns:
  200.     # - resp: server response if succesful
  201.     # - count: number of articles (string)
  202.     # - first: first article number (string)
  203.     # - last: last article number (string)
  204.     # - name: the group name
  205.  
  206.     def group(self, name):
  207.         resp = self.shortcmd('GROUP ' + name)
  208.         if resp[:3] <> '211':
  209.             raise error_reply, resp
  210.         words = string.split(resp)
  211.         count = first = last = 0
  212.         n = len(words)
  213.         if n > 1:
  214.             count = words[1]
  215.             if n > 2:
  216.                 first = words[2]
  217.                 if n > 3:
  218.                     last = words[3]
  219.                     if n > 4:
  220.                         name = string.lower(words[4])
  221.         return resp, count, first, last, name
  222.  
  223.     # Process a HELP command.  Returns:
  224.     # - resp: server response if succesful
  225.     # - list: list of strings
  226.  
  227.     def help(self):
  228.         return self.longcmd('HELP')
  229.  
  230.     # Internal: parse the response of a STAT, NEXT or LAST command
  231.     def statparse(self, resp):
  232.         if resp[:2] <> '22':
  233.             raise error_reply, resp
  234.         words = string.split(resp)
  235.         nr = 0
  236.         id = ''
  237.         n = len(words)
  238.         if n > 1:
  239.             nr = words[1]
  240.             if n > 2:
  241.                 id = string.lower(words[2])
  242.         return resp, nr, id
  243.  
  244.     # Internal: process a STAT, NEXT or LAST command
  245.     def statcmd(self, line):
  246.         resp = self.shortcmd(line)
  247.         return self.statparse(resp)
  248.  
  249.     # Process a STAT command.  Argument:
  250.     # - id: article number or message id
  251.     # Returns:
  252.     # - resp: server response if succesful
  253.     # - nr:   the article number
  254.     # - id:   the article id
  255.  
  256.     def stat(self, id):
  257.         return self.statcmd('STAT ' + id)
  258.  
  259.     # Process a NEXT command.  No arguments.  Return as for STAT
  260.  
  261.     def next(self):
  262.         return self.statcmd('NEXT')
  263.  
  264.     # Process a LAST command.  No arguments.  Return as for STAT
  265.  
  266.     def last(self):
  267.         return self.statcmd('LAST')
  268.  
  269.     # Internal: process a HEAD, BODY or ARTICLE command
  270.     def artcmd(self, line):
  271.         resp, list = self.longcmd(line)
  272.         resp, nr, id = self.statparse(resp)
  273.         return resp, nr, id, list
  274.  
  275.     # Process a HEAD command.  Argument:
  276.     # - id: article number or message id
  277.     # Returns:
  278.     # - resp: server response if succesful
  279.     # - list: the lines of the article's header
  280.  
  281.     def head(self, id):
  282.         return self.artcmd('HEAD ' + id)
  283.  
  284.     # Process a BODY command.  Argument:
  285.     # - id: article number or message id
  286.     # Returns:
  287.     # - resp: server response if succesful
  288.     # - list: the lines of the article's body
  289.  
  290.     def body(self, id):
  291.         return self.artcmd('BODY ' + id)
  292.  
  293.     # Process an ARTICLE command.  Argument:
  294.     # - id: article number or message id
  295.     # Returns:
  296.     # - resp: server response if succesful
  297.     # - list: the lines of the article
  298.  
  299.     def article(self, id):
  300.         return self.artcmd('ARTICLE ' + id)
  301.  
  302.     # Process a SLAVE command.  Returns:
  303.     # - resp: server response if succesful
  304.  
  305.     def slave(self):
  306.         return self.shortcmd('SLAVE')
  307.  
  308.     # Process an XHDR command (optional server extension).  Arguments:
  309.     # - hdr: the header type (e.g. 'subject')
  310.     # - str: an article nr, a message id, or a range nr1-nr2
  311.     # Returns:
  312.     # - resp: server response if succesful
  313.     # - list: list of (nr, value) strings
  314.  
  315.     def xhdr(self, hdr, str):
  316.         pat = re.compile('^([0-9]+) ?(.*)\n?')
  317.         resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str)
  318.         for i in range(len(lines)):
  319.             line = lines[i]
  320.             m = pat.match(line)
  321.             if m:
  322.                 lines[i] = m.group(1, 2)
  323.         return resp, lines
  324.  
  325.     # Process an XOVER command (optional server extension) Arguments:
  326.     # - start: start of range
  327.     # - end: end of range
  328.     # Returns:
  329.     # - resp: server response if succesful
  330.     # - list: list of (art-nr, subject, poster, date, id, refrences, size, lines)
  331.  
  332.     def xover(self,start,end):
  333.         resp, lines = self.longcmd('XOVER ' + start + '-' + end)
  334.         xover_lines = []
  335.         for line in lines:
  336.             elem = string.splitfields(line,"\t")
  337.             try:
  338.                 xover_lines.append((elem[0],
  339.                             elem[1],
  340.                             elem[2],
  341.                             elem[3],
  342.                             elem[4],
  343.                             string.split(elem[5]),
  344.                             elem[6],
  345.                             elem[7]))
  346.             except IndexError:
  347.                 raise error_data,line
  348.         return resp,xover_lines
  349.  
  350.     # Process an XGTITLE command (optional server extension) Arguments:
  351.     # - group: group name wildcard (i.e. news.*)
  352.     # Returns:
  353.     # - resp: server response if succesful
  354.     # - list: list of (name,title) strings
  355.  
  356.     def xgtitle(self, group):
  357.         line_pat = re.compile("^([^ \t]+)[ \t]+(.*)$")
  358.         resp, raw_lines = self.longcmd('XGTITLE ' + group)
  359.         lines = []
  360.         for raw_line in raw_lines:
  361.             match = line_pat.search(string.strip(raw_line))
  362.             if match:
  363.                 lines.append(match.group(1, 2))
  364.         return resp, lines
  365.  
  366.     # Process an XPATH command (optional server extension) Arguments:
  367.     # - id: Message id of article
  368.     # Returns:
  369.     # resp: server response if succesful
  370.     # path: directory path to article
  371.  
  372.     def xpath(self,id):
  373.         resp = self.shortcmd("XPATH " + id)
  374.         if resp[:3] <> '223':
  375.             raise error_reply, resp
  376.         try:
  377.             [resp_num, path] = string.split(resp)
  378.         except ValueError:
  379.             raise error_reply, resp
  380.         else:
  381.             return resp, path
  382.  
  383.     # Process the DATE command. Arguments:
  384.     # None
  385.     # Returns:
  386.     # resp: server response if succesful
  387.     # date: Date suitable for newnews/newgroups commands etc.
  388.     # time: Time suitable for newnews/newgroups commands etc.
  389.  
  390.     def date (self):
  391.         resp = self.shortcmd("DATE")
  392.         if resp[:3] <> '111':
  393.             raise error_reply, resp
  394.         elem = string.split(resp)
  395.         if len(elem) != 2:
  396.             raise error_data, resp
  397.         date = elem[1][2:8]
  398.         time = elem[1][-6:]
  399.         if len(date) != 6 or len(time) != 6:
  400.             raise error_data, resp
  401.         return resp, date, time
  402.  
  403.  
  404.     # Process a POST command.  Arguments:
  405.     # - f: file containing the article
  406.     # Returns:
  407.     # - resp: server response if succesful
  408.  
  409.     def post(self, f):
  410.         resp = self.shortcmd('POST')
  411.         # Raises error_??? if posting is not allowed
  412.         if resp[0] <> '3':
  413.             raise error_reply, resp
  414.         while 1:
  415.             line = f.readline()
  416.             if not line:
  417.                 break
  418.             if line[-1] == '\n':
  419.                 line = line[:-1]
  420.             if line[:1] == '.':
  421.                 line = '.' + line
  422.             self.putline(line)
  423.         self.putline('.')
  424.         return self.getresp()
  425.  
  426.     # Process an IHAVE command.  Arguments:
  427.     # - id: message-id of the article
  428.     # - f:  file containing the article
  429.     # Returns:
  430.     # - resp: server response if succesful
  431.     # Note that if the server refuses the article an exception is raised
  432.  
  433.     def ihave(self, id, f):
  434.         resp = self.shortcmd('IHAVE ' + id)
  435.         # Raises error_??? if the server already has it
  436.         if resp[0] <> '3':
  437.             raise error_reply, resp
  438.         while 1:
  439.             line = f.readline()
  440.             if not line:
  441.                 break
  442.             if line[-1] == '\n':
  443.                 line = line[:-1]
  444.             if line[:1] == '.':
  445.                 line = '.' + line
  446.             self.putline(line)
  447.         self.putline('.')
  448.         return self.getresp()
  449.  
  450.      # Process a QUIT command and close the socket.  Returns:
  451.      # - resp: server response if succesful
  452.  
  453.     def quit(self):
  454.         resp = self.shortcmd('QUIT')
  455.         self.file.close()
  456.         self.sock.close()
  457.         del self.file, self.sock
  458.         return resp
  459.  
  460.  
  461. # Minimal test function
  462. def _test():
  463.     s = NNTP('news')
  464.     resp, count, first, last, name = s.group('comp.lang.python')
  465.     print resp
  466.     print 'Group', name, 'has', count, 'articles, range', first, 'to', last
  467.     resp, subs = s.xhdr('subject', first + '-' + last)
  468.     print resp
  469.     for item in subs:
  470.         print "%7s %s" % item
  471.     resp = s.quit()
  472.     print resp
  473.  
  474.  
  475. # Run the test when run as a script
  476. if __name__ == '__main__':
  477.     _test()
  478.