1 """An NNTP client class based on RFC 977: Network News Transfer Protocol.
5 >>> from nntplib import NNTP
7 >>> resp, count, first, last, name = s.group('comp.lang.python')
8 >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
9 Group comp.lang.python has 51 articles, range 5770 to 5821
10 >>> resp, subs = s.xhdr('subject', first + '-' + last)
14 Here 'resp' is the server response line.
15 Error responses are turned into exceptions.
17 To post an article from a file:
18 >>> f = open(filename, 'r') # file containing article, including header
22 For descriptions of all methods, read the comments in the code below.
23 Note that all arguments and return values representing article numbers
24 are strings, not numbers, since they are rarely used for calculations.
27 # RFC 977 by Brian Kantor and Phil Lapsley.
28 # xover, xgtitle, xpath, date methods by Kevan Heydon
38 # Exceptions raised when an error or invalid response is received
39 class NNTPError(Exception):
40 """Base class for all nntplib exceptions"""
41 def __init__(self
, *args
):
42 apply(Exception.__init
__, (self
,)+args
)
44 self
.response
= args
[0]
46 self
.response
= 'No response given'
48 class NNTPReplyError(NNTPError
):
49 """Unexpected [123]xx reply"""
52 class NNTPTemporaryError(NNTPError
):
56 class NNTPPermanentError(NNTPError
):
60 class NNTPProtocolError(NNTPError
):
61 """Response does not begin with [1-5]"""
64 class NNTPDataError(NNTPError
):
65 """Error in response data"""
68 # for backwards compatibility
69 error_reply
= NNTPReplyError
70 error_temp
= NNTPTemporaryError
71 error_perm
= NNTPPermanentError
72 error_proto
= NNTPProtocolError
73 error_data
= NNTPDataError
77 # Standard port used by NNTP servers
81 # Response numbers that are followed by additional text (e.g. article)
82 LONGRESP
= ['100', '215', '220', '221', '222', '224', '230', '231', '282']
85 # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
92 def __init__(self
, host
, port
=NNTP_PORT
, user
=None, password
=None,
94 """Initialize an instance. Arguments:
95 - host: hostname to connect to
96 - port: port to connect to (default the standard NNTP port)
97 - user: username to authenticate with
98 - password: password to use with username
99 - readermode: if true, send 'mode reader' command after
102 readermode is sometimes necessary if you are connecting to an
103 NNTP server on the local machine and intend to call
104 reader-specific comamnds, such as `group'. If you get
105 unexpected NNTPPermanentErrors, you might need to set
110 self
.sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
111 self
.sock
.connect(self
.host
, self
.port
)
112 self
.file = self
.sock
.makefile('rb')
114 self
.welcome
= self
.getresp()
117 self
.welcome
= self
.shortcmd('mode reader')
118 except NNTPPermanentError
:
119 # error 500, probably 'not implemented'
122 resp
= self
.shortcmd('authinfo user '+user
)
123 if resp
[:3] == '381':
125 raise NNTPReplyError(resp
)
127 resp
= self
.shortcmd(
128 'authinfo pass '+password
)
129 if resp
[:3] != '281':
130 raise NNTPPermanentError(resp
)
132 # Get the welcome message from the server
133 # (this is read and squirreled away by __init__()).
134 # If the response code is 200, posting is allowed;
135 # if it 201, posting is not allowed
137 def getwelcome(self
):
138 """Get the welcome message from the server
139 (this is read and squirreled away by __init__()).
140 If the response code is 200, posting is allowed;
141 if it 201, posting is not allowed."""
143 if self
.debugging
: print '*welcome*', `self
.welcome`
146 def set_debuglevel(self
, level
):
147 """Set the debugging level. Argument 'level' means:
148 0: no debugging output (default)
149 1: print commands and responses but not body text etc.
150 2: also print raw lines read and sent before stripping CR/LF"""
152 self
.debugging
= level
153 debug
= set_debuglevel
155 def putline(self
, line
):
156 """Internal: send one line to the server, appending CRLF."""
158 if self
.debugging
> 1: print '*put*', `line`
161 def putcmd(self
, line
):
162 """Internal: send one command to the server (through putline())."""
163 if self
.debugging
: print '*cmd*', `line`
167 """Internal: return one line from the server, stripping CRLF.
168 Raise EOFError if the connection is closed."""
169 line
= self
.file.readline()
170 if self
.debugging
> 1:
171 print '*get*', `line`
172 if not line
: raise EOFError
173 if line
[-2:] == CRLF
: line
= line
[:-2]
174 elif line
[-1:] in CRLF
: line
= line
[:-1]
178 """Internal: get a response from the server.
179 Raise various errors if the response indicates an error."""
180 resp
= self
.getline()
181 if self
.debugging
: print '*resp*', `resp`
184 raise NNTPTemporaryError(resp
)
186 raise NNTPPermanentError(resp
)
188 raise NNTPProtocolError(resp
)
191 def getlongresp(self
):
192 """Internal: get a response plus following text from the server.
193 Raise various errors if the response indicates an error."""
194 resp
= self
.getresp()
195 if resp
[:3] not in LONGRESP
:
196 raise NNTPReplyError(resp
)
199 line
= self
.getline()
207 def shortcmd(self
, line
):
208 """Internal: send a command and get the response."""
210 return self
.getresp()
212 def longcmd(self
, line
):
213 """Internal: send a command and get the response plus following text."""
215 return self
.getlongresp()
217 def newgroups(self
, date
, time
):
218 """Process a NEWGROUPS command. Arguments:
219 - date: string 'yymmdd' indicating the date
220 - time: string 'hhmmss' indicating the time
222 - resp: server response if succesful
223 - list: list of newsgroup names"""
225 return self
.longcmd('NEWGROUPS ' + date
+ ' ' + time
)
227 def newnews(self
, group
, date
, time
):
228 """Process a NEWNEWS command. Arguments:
229 - group: group name or '*'
230 - date: string 'yymmdd' indicating the date
231 - time: string 'hhmmss' indicating the time
233 - resp: server response if succesful
234 - list: list of article ids"""
236 cmd
= 'NEWNEWS ' + group
+ ' ' + date
+ ' ' + time
237 return self
.longcmd(cmd
)
240 """Process a LIST command. Return:
241 - resp: server response if succesful
242 - list: list of (group, last, first, flag) (strings)"""
244 resp
, list = self
.longcmd('LIST')
245 for i
in range(len(list)):
246 # Parse lines into "group last first flag"
247 list[i
] = tuple(string
.split(list[i
]))
250 def group(self
, name
):
251 """Process a GROUP command. Argument:
252 - group: the group name
254 - resp: server response if succesful
255 - count: number of articles (string)
256 - first: first article number (string)
257 - last: last article number (string)
258 - name: the group name"""
260 resp
= self
.shortcmd('GROUP ' + name
)
261 if resp
[:3] <> '211':
262 raise NNTPReplyError(resp
)
263 words
= string
.split(resp
)
264 count
= first
= last
= 0
273 name
= string
.lower(words
[4])
274 return resp
, count
, first
, last
, name
277 """Process a HELP command. Returns:
278 - resp: server response if succesful
279 - list: list of strings"""
281 return self
.longcmd('HELP')
283 def statparse(self
, resp
):
284 """Internal: parse the response of a STAT, NEXT or LAST command."""
286 raise NNTPReplyError(resp
)
287 words
= string
.split(resp
)
297 def statcmd(self
, line
):
298 """Internal: process a STAT, NEXT or LAST command."""
299 resp
= self
.shortcmd(line
)
300 return self
.statparse(resp
)
303 """Process a STAT command. Argument:
304 - id: article number or message id
306 - resp: server response if succesful
307 - nr: the article number
308 - id: the article id"""
310 return self
.statcmd('STAT ' + id)
313 """Process a NEXT command. No arguments. Return as for STAT."""
314 return self
.statcmd('NEXT')
317 """Process a LAST command. No arguments. Return as for STAT."""
318 return self
.statcmd('LAST')
320 def artcmd(self
, line
):
321 """Internal: process a HEAD, BODY or ARTICLE command."""
322 resp
, list = self
.longcmd(line
)
323 resp
, nr
, id = self
.statparse(resp
)
324 return resp
, nr
, id, list
327 """Process a HEAD command. Argument:
328 - id: article number or message id
330 - resp: server response if succesful
333 - list: the lines of the article's header"""
335 return self
.artcmd('HEAD ' + id)
338 """Process a BODY command. Argument:
339 - id: article number or message id
341 - resp: server response if succesful
344 - list: the lines of the article's body"""
346 return self
.artcmd('BODY ' + id)
348 def article(self
, id):
349 """Process an ARTICLE command. Argument:
350 - id: article number or message id
352 - resp: server response if succesful
355 - list: the lines of the article"""
357 return self
.artcmd('ARTICLE ' + id)
360 """Process a SLAVE command. Returns:
361 - resp: server response if succesful"""
363 return self
.shortcmd('SLAVE')
365 def xhdr(self
, hdr
, str):
366 """Process an XHDR command (optional server extension). Arguments:
367 - hdr: the header type (e.g. 'subject')
368 - str: an article nr, a message id, or a range nr1-nr2
370 - resp: server response if succesful
371 - list: list of (nr, value) strings"""
373 pat
= re
.compile('^([0-9]+) ?(.*)\n?')
374 resp
, lines
= self
.longcmd('XHDR ' + hdr
+ ' ' + str)
375 for i
in range(len(lines
)):
379 lines
[i
] = m
.group(1, 2)
382 def xover(self
,start
,end
):
383 """Process an XOVER command (optional server extension) Arguments:
384 - start: start of range
387 - resp: server response if succesful
388 - list: list of (art-nr, subject, poster, date,
389 id, references, size, lines)"""
391 resp
, lines
= self
.longcmd('XOVER ' + start
+ '-' + end
)
394 elem
= string
.splitfields(line
,"\t")
396 xover_lines
.append((elem
[0],
401 string
.split(elem
[5]),
405 raise NNTPDataError(line
)
406 return resp
,xover_lines
408 def xgtitle(self
, group
):
409 """Process an XGTITLE command (optional server extension) Arguments:
410 - group: group name wildcard (i.e. news.*)
412 - resp: server response if succesful
413 - list: list of (name,title) strings"""
415 line_pat
= re
.compile("^([^ \t]+)[ \t]+(.*)$")
416 resp
, raw_lines
= self
.longcmd('XGTITLE ' + group
)
418 for raw_line
in raw_lines
:
419 match
= line_pat
.search(string
.strip(raw_line
))
421 lines
.append(match
.group(1, 2))
425 """Process an XPATH command (optional server extension) Arguments:
426 - id: Message id of article
428 resp: server response if succesful
429 path: directory path to article"""
431 resp
= self
.shortcmd("XPATH " + id)
432 if resp
[:3] <> '223':
433 raise NNTPReplyError(resp
)
435 [resp_num
, path
] = string
.split(resp
)
437 raise NNTPReplyError(resp
)
442 """Process the DATE command. Arguments:
445 resp: server response if succesful
446 date: Date suitable for newnews/newgroups commands etc.
447 time: Time suitable for newnews/newgroups commands etc."""
449 resp
= self
.shortcmd("DATE")
450 if resp
[:3] <> '111':
451 raise NNTPReplyError(resp
)
452 elem
= string
.split(resp
)
454 raise NNTPDataError(resp
)
457 if len(date
) != 6 or len(time
) != 6:
458 raise NNTPDataError(resp
)
459 return resp
, date
, time
463 """Process a POST command. Arguments:
464 - f: file containing the article
466 - resp: server response if succesful"""
468 resp
= self
.shortcmd('POST')
469 # Raises error_??? if posting is not allowed
471 raise NNTPReplyError(resp
)
482 return self
.getresp()
484 def ihave(self
, id, f
):
485 """Process an IHAVE command. Arguments:
486 - id: message-id of the article
487 - f: file containing the article
489 - resp: server response if succesful
490 Note that if the server refuses the article an exception is raised."""
492 resp
= self
.shortcmd('IHAVE ' + id)
493 # Raises error_??? if the server already has it
495 raise NNTPReplyError(resp
)
506 return self
.getresp()
509 """Process a QUIT command and close the socket. Returns:
510 - resp: server response if succesful"""
512 resp
= self
.shortcmd('QUIT')
515 del self
.file, self
.sock
520 """Minimal test function."""
521 s
= NNTP('news', readermode
='reader')
522 resp
, count
, first
, last
, name
= s
.group('comp.lang.python')
524 print 'Group', name
, 'has', count
, 'articles, range', first
, 'to', last
525 resp
, subs
= s
.xhdr('subject', first
+ '-' + last
)
528 print "%7s %s" % item
533 # Run the test when run as a script
534 if __name__
== '__main__':