Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3....
File: nntplib.py
"""An NNTP client class based on:
[0] Fix | Delete
- RFC 977: Network News Transfer Protocol
[1] Fix | Delete
- RFC 2980: Common NNTP Extensions
[2] Fix | Delete
- RFC 3977: Network News Transfer Protocol (version 2)
[3] Fix | Delete
[4] Fix | Delete
Example:
[5] Fix | Delete
[6] Fix | Delete
>>> from nntplib import NNTP
[7] Fix | Delete
>>> s = NNTP('news')
[8] Fix | Delete
>>> resp, count, first, last, name = s.group('comp.lang.python')
[9] Fix | Delete
>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
[10] Fix | Delete
Group comp.lang.python has 51 articles, range 5770 to 5821
[11] Fix | Delete
>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last))
[12] Fix | Delete
>>> resp = s.quit()
[13] Fix | Delete
>>>
[14] Fix | Delete
[15] Fix | Delete
Here 'resp' is the server response line.
[16] Fix | Delete
Error responses are turned into exceptions.
[17] Fix | Delete
[18] Fix | Delete
To post an article from a file:
[19] Fix | Delete
>>> f = open(filename, 'rb') # file containing article, including header
[20] Fix | Delete
>>> resp = s.post(f)
[21] Fix | Delete
>>>
[22] Fix | Delete
[23] Fix | Delete
For descriptions of all methods, read the comments in the code below.
[24] Fix | Delete
Note that all arguments and return values representing article numbers
[25] Fix | Delete
are strings, not numbers, since they are rarely used for calculations.
[26] Fix | Delete
"""
[27] Fix | Delete
[28] Fix | Delete
# RFC 977 by Brian Kantor and Phil Lapsley.
[29] Fix | Delete
# xover, xgtitle, xpath, date methods by Kevan Heydon
[30] Fix | Delete
[31] Fix | Delete
# Incompatible changes from the 2.x nntplib:
[32] Fix | Delete
# - all commands are encoded as UTF-8 data (using the "surrogateescape"
[33] Fix | Delete
# error handler), except for raw message data (POST, IHAVE)
[34] Fix | Delete
# - all responses are decoded as UTF-8 data (using the "surrogateescape"
[35] Fix | Delete
# error handler), except for raw message data (ARTICLE, HEAD, BODY)
[36] Fix | Delete
# - the `file` argument to various methods is keyword-only
[37] Fix | Delete
#
[38] Fix | Delete
# - NNTP.date() returns a datetime object
[39] Fix | Delete
# - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object,
[40] Fix | Delete
# rather than a pair of (date, time) strings.
[41] Fix | Delete
# - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples
[42] Fix | Delete
# - NNTP.descriptions() returns a dict mapping group names to descriptions
[43] Fix | Delete
# - NNTP.xover() returns a list of dicts mapping field names (header or metadata)
[44] Fix | Delete
# to field values; each dict representing a message overview.
[45] Fix | Delete
# - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo)
[46] Fix | Delete
# tuple.
[47] Fix | Delete
# - the "internal" methods have been marked private (they now start with
[48] Fix | Delete
# an underscore)
[49] Fix | Delete
[50] Fix | Delete
# Other changes from the 2.x/3.1 nntplib:
[51] Fix | Delete
# - automatic querying of capabilities at connect
[52] Fix | Delete
# - New method NNTP.getcapabilities()
[53] Fix | Delete
# - New method NNTP.over()
[54] Fix | Delete
# - New helper function decode_header()
[55] Fix | Delete
# - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and
[56] Fix | Delete
# arbitrary iterables yielding lines.
[57] Fix | Delete
# - An extensive test suite :-)
[58] Fix | Delete
[59] Fix | Delete
# TODO:
[60] Fix | Delete
# - return structured data (GroupInfo etc.) everywhere
[61] Fix | Delete
# - support HDR
[62] Fix | Delete
[63] Fix | Delete
# Imports
[64] Fix | Delete
import re
[65] Fix | Delete
import socket
[66] Fix | Delete
import collections
[67] Fix | Delete
import datetime
[68] Fix | Delete
import warnings
[69] Fix | Delete
[70] Fix | Delete
try:
[71] Fix | Delete
import ssl
[72] Fix | Delete
except ImportError:
[73] Fix | Delete
_have_ssl = False
[74] Fix | Delete
else:
[75] Fix | Delete
_have_ssl = True
[76] Fix | Delete
[77] Fix | Delete
from email.header import decode_header as _email_decode_header
[78] Fix | Delete
from socket import _GLOBAL_DEFAULT_TIMEOUT
[79] Fix | Delete
[80] Fix | Delete
__all__ = ["NNTP",
[81] Fix | Delete
"NNTPError", "NNTPReplyError", "NNTPTemporaryError",
[82] Fix | Delete
"NNTPPermanentError", "NNTPProtocolError", "NNTPDataError",
[83] Fix | Delete
"decode_header",
[84] Fix | Delete
]
[85] Fix | Delete
[86] Fix | Delete
# maximal line length when calling readline(). This is to prevent
[87] Fix | Delete
# reading arbitrary length lines. RFC 3977 limits NNTP line length to
[88] Fix | Delete
# 512 characters, including CRLF. We have selected 2048 just to be on
[89] Fix | Delete
# the safe side.
[90] Fix | Delete
_MAXLINE = 2048
[91] Fix | Delete
[92] Fix | Delete
[93] Fix | Delete
# Exceptions raised when an error or invalid response is received
[94] Fix | Delete
class NNTPError(Exception):
[95] Fix | Delete
"""Base class for all nntplib exceptions"""
[96] Fix | Delete
def __init__(self, *args):
[97] Fix | Delete
Exception.__init__(self, *args)
[98] Fix | Delete
try:
[99] Fix | Delete
self.response = args[0]
[100] Fix | Delete
except IndexError:
[101] Fix | Delete
self.response = 'No response given'
[102] Fix | Delete
[103] Fix | Delete
class NNTPReplyError(NNTPError):
[104] Fix | Delete
"""Unexpected [123]xx reply"""
[105] Fix | Delete
pass
[106] Fix | Delete
[107] Fix | Delete
class NNTPTemporaryError(NNTPError):
[108] Fix | Delete
"""4xx errors"""
[109] Fix | Delete
pass
[110] Fix | Delete
[111] Fix | Delete
class NNTPPermanentError(NNTPError):
[112] Fix | Delete
"""5xx errors"""
[113] Fix | Delete
pass
[114] Fix | Delete
[115] Fix | Delete
class NNTPProtocolError(NNTPError):
[116] Fix | Delete
"""Response does not begin with [1-5]"""
[117] Fix | Delete
pass
[118] Fix | Delete
[119] Fix | Delete
class NNTPDataError(NNTPError):
[120] Fix | Delete
"""Error in response data"""
[121] Fix | Delete
pass
[122] Fix | Delete
[123] Fix | Delete
[124] Fix | Delete
# Standard port used by NNTP servers
[125] Fix | Delete
NNTP_PORT = 119
[126] Fix | Delete
NNTP_SSL_PORT = 563
[127] Fix | Delete
[128] Fix | Delete
# Response numbers that are followed by additional text (e.g. article)
[129] Fix | Delete
_LONGRESP = {
[130] Fix | Delete
'100', # HELP
[131] Fix | Delete
'101', # CAPABILITIES
[132] Fix | Delete
'211', # LISTGROUP (also not multi-line with GROUP)
[133] Fix | Delete
'215', # LIST
[134] Fix | Delete
'220', # ARTICLE
[135] Fix | Delete
'221', # HEAD, XHDR
[136] Fix | Delete
'222', # BODY
[137] Fix | Delete
'224', # OVER, XOVER
[138] Fix | Delete
'225', # HDR
[139] Fix | Delete
'230', # NEWNEWS
[140] Fix | Delete
'231', # NEWGROUPS
[141] Fix | Delete
'282', # XGTITLE
[142] Fix | Delete
}
[143] Fix | Delete
[144] Fix | Delete
# Default decoded value for LIST OVERVIEW.FMT if not supported
[145] Fix | Delete
_DEFAULT_OVERVIEW_FMT = [
[146] Fix | Delete
"subject", "from", "date", "message-id", "references", ":bytes", ":lines"]
[147] Fix | Delete
[148] Fix | Delete
# Alternative names allowed in LIST OVERVIEW.FMT response
[149] Fix | Delete
_OVERVIEW_FMT_ALTERNATIVES = {
[150] Fix | Delete
'bytes': ':bytes',
[151] Fix | Delete
'lines': ':lines',
[152] Fix | Delete
}
[153] Fix | Delete
[154] Fix | Delete
# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
[155] Fix | Delete
_CRLF = b'\r\n'
[156] Fix | Delete
[157] Fix | Delete
GroupInfo = collections.namedtuple('GroupInfo',
[158] Fix | Delete
['group', 'last', 'first', 'flag'])
[159] Fix | Delete
[160] Fix | Delete
ArticleInfo = collections.namedtuple('ArticleInfo',
[161] Fix | Delete
['number', 'message_id', 'lines'])
[162] Fix | Delete
[163] Fix | Delete
[164] Fix | Delete
# Helper function(s)
[165] Fix | Delete
def decode_header(header_str):
[166] Fix | Delete
"""Takes a unicode string representing a munged header value
[167] Fix | Delete
and decodes it as a (possibly non-ASCII) readable value."""
[168] Fix | Delete
parts = []
[169] Fix | Delete
for v, enc in _email_decode_header(header_str):
[170] Fix | Delete
if isinstance(v, bytes):
[171] Fix | Delete
parts.append(v.decode(enc or 'ascii'))
[172] Fix | Delete
else:
[173] Fix | Delete
parts.append(v)
[174] Fix | Delete
return ''.join(parts)
[175] Fix | Delete
[176] Fix | Delete
def _parse_overview_fmt(lines):
[177] Fix | Delete
"""Parse a list of string representing the response to LIST OVERVIEW.FMT
[178] Fix | Delete
and return a list of header/metadata names.
[179] Fix | Delete
Raises NNTPDataError if the response is not compliant
[180] Fix | Delete
(cf. RFC 3977, section 8.4)."""
[181] Fix | Delete
fmt = []
[182] Fix | Delete
for line in lines:
[183] Fix | Delete
if line[0] == ':':
[184] Fix | Delete
# Metadata name (e.g. ":bytes")
[185] Fix | Delete
name, _, suffix = line[1:].partition(':')
[186] Fix | Delete
name = ':' + name
[187] Fix | Delete
else:
[188] Fix | Delete
# Header name (e.g. "Subject:" or "Xref:full")
[189] Fix | Delete
name, _, suffix = line.partition(':')
[190] Fix | Delete
name = name.lower()
[191] Fix | Delete
name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name)
[192] Fix | Delete
# Should we do something with the suffix?
[193] Fix | Delete
fmt.append(name)
[194] Fix | Delete
defaults = _DEFAULT_OVERVIEW_FMT
[195] Fix | Delete
if len(fmt) < len(defaults):
[196] Fix | Delete
raise NNTPDataError("LIST OVERVIEW.FMT response too short")
[197] Fix | Delete
if fmt[:len(defaults)] != defaults:
[198] Fix | Delete
raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields")
[199] Fix | Delete
return fmt
[200] Fix | Delete
[201] Fix | Delete
def _parse_overview(lines, fmt, data_process_func=None):
[202] Fix | Delete
"""Parse the response to an OVER or XOVER command according to the
[203] Fix | Delete
overview format `fmt`."""
[204] Fix | Delete
n_defaults = len(_DEFAULT_OVERVIEW_FMT)
[205] Fix | Delete
overview = []
[206] Fix | Delete
for line in lines:
[207] Fix | Delete
fields = {}
[208] Fix | Delete
article_number, *tokens = line.split('\t')
[209] Fix | Delete
article_number = int(article_number)
[210] Fix | Delete
for i, token in enumerate(tokens):
[211] Fix | Delete
if i >= len(fmt):
[212] Fix | Delete
# XXX should we raise an error? Some servers might not
[213] Fix | Delete
# support LIST OVERVIEW.FMT and still return additional
[214] Fix | Delete
# headers.
[215] Fix | Delete
continue
[216] Fix | Delete
field_name = fmt[i]
[217] Fix | Delete
is_metadata = field_name.startswith(':')
[218] Fix | Delete
if i >= n_defaults and not is_metadata:
[219] Fix | Delete
# Non-default header names are included in full in the response
[220] Fix | Delete
# (unless the field is totally empty)
[221] Fix | Delete
h = field_name + ": "
[222] Fix | Delete
if token and token[:len(h)].lower() != h:
[223] Fix | Delete
raise NNTPDataError("OVER/XOVER response doesn't include "
[224] Fix | Delete
"names of additional headers")
[225] Fix | Delete
token = token[len(h):] if token else None
[226] Fix | Delete
fields[fmt[i]] = token
[227] Fix | Delete
overview.append((article_number, fields))
[228] Fix | Delete
return overview
[229] Fix | Delete
[230] Fix | Delete
def _parse_datetime(date_str, time_str=None):
[231] Fix | Delete
"""Parse a pair of (date, time) strings, and return a datetime object.
[232] Fix | Delete
If only the date is given, it is assumed to be date and time
[233] Fix | Delete
concatenated together (e.g. response to the DATE command).
[234] Fix | Delete
"""
[235] Fix | Delete
if time_str is None:
[236] Fix | Delete
time_str = date_str[-6:]
[237] Fix | Delete
date_str = date_str[:-6]
[238] Fix | Delete
hours = int(time_str[:2])
[239] Fix | Delete
minutes = int(time_str[2:4])
[240] Fix | Delete
seconds = int(time_str[4:])
[241] Fix | Delete
year = int(date_str[:-4])
[242] Fix | Delete
month = int(date_str[-4:-2])
[243] Fix | Delete
day = int(date_str[-2:])
[244] Fix | Delete
# RFC 3977 doesn't say how to interpret 2-char years. Assume that
[245] Fix | Delete
# there are no dates before 1970 on Usenet.
[246] Fix | Delete
if year < 70:
[247] Fix | Delete
year += 2000
[248] Fix | Delete
elif year < 100:
[249] Fix | Delete
year += 1900
[250] Fix | Delete
return datetime.datetime(year, month, day, hours, minutes, seconds)
[251] Fix | Delete
[252] Fix | Delete
def _unparse_datetime(dt, legacy=False):
[253] Fix | Delete
"""Format a date or datetime object as a pair of (date, time) strings
[254] Fix | Delete
in the format required by the NEWNEWS and NEWGROUPS commands. If a
[255] Fix | Delete
date object is passed, the time is assumed to be midnight (00h00).
[256] Fix | Delete
[257] Fix | Delete
The returned representation depends on the legacy flag:
[258] Fix | Delete
* if legacy is False (the default):
[259] Fix | Delete
date has the YYYYMMDD format and time the HHMMSS format
[260] Fix | Delete
* if legacy is True:
[261] Fix | Delete
date has the YYMMDD format and time the HHMMSS format.
[262] Fix | Delete
RFC 3977 compliant servers should understand both formats; therefore,
[263] Fix | Delete
legacy is only needed when talking to old servers.
[264] Fix | Delete
"""
[265] Fix | Delete
if not isinstance(dt, datetime.datetime):
[266] Fix | Delete
time_str = "000000"
[267] Fix | Delete
else:
[268] Fix | Delete
time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt)
[269] Fix | Delete
y = dt.year
[270] Fix | Delete
if legacy:
[271] Fix | Delete
y = y % 100
[272] Fix | Delete
date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt)
[273] Fix | Delete
else:
[274] Fix | Delete
date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt)
[275] Fix | Delete
return date_str, time_str
[276] Fix | Delete
[277] Fix | Delete
[278] Fix | Delete
if _have_ssl:
[279] Fix | Delete
[280] Fix | Delete
def _encrypt_on(sock, context, hostname):
[281] Fix | Delete
"""Wrap a socket in SSL/TLS. Arguments:
[282] Fix | Delete
- sock: Socket to wrap
[283] Fix | Delete
- context: SSL context to use for the encrypted connection
[284] Fix | Delete
Returns:
[285] Fix | Delete
- sock: New, encrypted socket.
[286] Fix | Delete
"""
[287] Fix | Delete
# Generate a default SSL context if none was passed.
[288] Fix | Delete
if context is None:
[289] Fix | Delete
context = ssl._create_stdlib_context()
[290] Fix | Delete
return context.wrap_socket(sock, server_hostname=hostname)
[291] Fix | Delete
[292] Fix | Delete
[293] Fix | Delete
# The classes themselves
[294] Fix | Delete
class _NNTPBase:
[295] Fix | Delete
# UTF-8 is the character set for all NNTP commands and responses: they
[296] Fix | Delete
# are automatically encoded (when sending) and decoded (and receiving)
[297] Fix | Delete
# by this class.
[298] Fix | Delete
# However, some multi-line data blocks can contain arbitrary bytes (for
[299] Fix | Delete
# example, latin-1 or utf-16 data in the body of a message). Commands
[300] Fix | Delete
# taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message
[301] Fix | Delete
# data will therefore only accept and produce bytes objects.
[302] Fix | Delete
# Furthermore, since there could be non-compliant servers out there,
[303] Fix | Delete
# we use 'surrogateescape' as the error handler for fault tolerance
[304] Fix | Delete
# and easy round-tripping. This could be useful for some applications
[305] Fix | Delete
# (e.g. NNTP gateways).
[306] Fix | Delete
[307] Fix | Delete
encoding = 'utf-8'
[308] Fix | Delete
errors = 'surrogateescape'
[309] Fix | Delete
[310] Fix | Delete
def __init__(self, file, host,
[311] Fix | Delete
readermode=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):
[312] Fix | Delete
"""Initialize an instance. Arguments:
[313] Fix | Delete
- file: file-like object (open for read/write in binary mode)
[314] Fix | Delete
- host: hostname of the server
[315] Fix | Delete
- readermode: if true, send 'mode reader' command after
[316] Fix | Delete
connecting.
[317] Fix | Delete
- timeout: timeout (in seconds) used for socket connections
[318] Fix | Delete
[319] Fix | Delete
readermode is sometimes necessary if you are connecting to an
[320] Fix | Delete
NNTP server on the local machine and intend to call
[321] Fix | Delete
reader-specific commands, such as `group'. If you get
[322] Fix | Delete
unexpected NNTPPermanentErrors, you might need to set
[323] Fix | Delete
readermode.
[324] Fix | Delete
"""
[325] Fix | Delete
self.host = host
[326] Fix | Delete
self.file = file
[327] Fix | Delete
self.debugging = 0
[328] Fix | Delete
self.welcome = self._getresp()
[329] Fix | Delete
[330] Fix | Delete
# Inquire about capabilities (RFC 3977).
[331] Fix | Delete
self._caps = None
[332] Fix | Delete
self.getcapabilities()
[333] Fix | Delete
[334] Fix | Delete
# 'MODE READER' is sometimes necessary to enable 'reader' mode.
[335] Fix | Delete
# However, the order in which 'MODE READER' and 'AUTHINFO' need to
[336] Fix | Delete
# arrive differs between some NNTP servers. If _setreadermode() fails
[337] Fix | Delete
# with an authorization failed error, it will set this to True;
[338] Fix | Delete
# the login() routine will interpret that as a request to try again
[339] Fix | Delete
# after performing its normal function.
[340] Fix | Delete
# Enable only if we're not already in READER mode anyway.
[341] Fix | Delete
self.readermode_afterauth = False
[342] Fix | Delete
if readermode and 'READER' not in self._caps:
[343] Fix | Delete
self._setreadermode()
[344] Fix | Delete
if not self.readermode_afterauth:
[345] Fix | Delete
# Capabilities might have changed after MODE READER
[346] Fix | Delete
self._caps = None
[347] Fix | Delete
self.getcapabilities()
[348] Fix | Delete
[349] Fix | Delete
# RFC 4642 2.2.2: Both the client and the server MUST know if there is
[350] Fix | Delete
# a TLS session active. A client MUST NOT attempt to start a TLS
[351] Fix | Delete
# session if a TLS session is already active.
[352] Fix | Delete
self.tls_on = False
[353] Fix | Delete
[354] Fix | Delete
# Log in and encryption setup order is left to subclasses.
[355] Fix | Delete
self.authenticated = False
[356] Fix | Delete
[357] Fix | Delete
def __enter__(self):
[358] Fix | Delete
return self
[359] Fix | Delete
[360] Fix | Delete
def __exit__(self, *args):
[361] Fix | Delete
is_connected = lambda: hasattr(self, "file")
[362] Fix | Delete
if is_connected():
[363] Fix | Delete
try:
[364] Fix | Delete
self.quit()
[365] Fix | Delete
except (OSError, EOFError):
[366] Fix | Delete
pass
[367] Fix | Delete
finally:
[368] Fix | Delete
if is_connected():
[369] Fix | Delete
self._close()
[370] Fix | Delete
[371] Fix | Delete
def getwelcome(self):
[372] Fix | Delete
"""Get the welcome message from the server
[373] Fix | Delete
(this is read and squirreled away by __init__()).
[374] Fix | Delete
If the response code is 200, posting is allowed;
[375] Fix | Delete
if it 201, posting is not allowed."""
[376] Fix | Delete
[377] Fix | Delete
if self.debugging: print('*welcome*', repr(self.welcome))
[378] Fix | Delete
return self.welcome
[379] Fix | Delete
[380] Fix | Delete
def getcapabilities(self):
[381] Fix | Delete
"""Get the server capabilities, as read by __init__().
[382] Fix | Delete
If the CAPABILITIES command is not supported, an empty dict is
[383] Fix | Delete
returned."""
[384] Fix | Delete
if self._caps is None:
[385] Fix | Delete
self.nntp_version = 1
[386] Fix | Delete
self.nntp_implementation = None
[387] Fix | Delete
try:
[388] Fix | Delete
resp, caps = self.capabilities()
[389] Fix | Delete
except (NNTPPermanentError, NNTPTemporaryError):
[390] Fix | Delete
# Server doesn't support capabilities
[391] Fix | Delete
self._caps = {}
[392] Fix | Delete
else:
[393] Fix | Delete
self._caps = caps
[394] Fix | Delete
if 'VERSION' in caps:
[395] Fix | Delete
# The server can advertise several supported versions,
[396] Fix | Delete
# choose the highest.
[397] Fix | Delete
self.nntp_version = max(map(int, caps['VERSION']))
[398] Fix | Delete
if 'IMPLEMENTATION' in caps:
[399] Fix | Delete
self.nntp_implementation = ' '.join(caps['IMPLEMENTATION'])
[400] Fix | Delete
return self._caps
[401] Fix | Delete
[402] Fix | Delete
def set_debuglevel(self, level):
[403] Fix | Delete
"""Set the debugging level. Argument 'level' means:
[404] Fix | Delete
0: no debugging output (default)
[405] Fix | Delete
1: print commands and responses but not body text etc.
[406] Fix | Delete
2: also print raw lines read and sent before stripping CR/LF"""
[407] Fix | Delete
[408] Fix | Delete
self.debugging = level
[409] Fix | Delete
debug = set_debuglevel
[410] Fix | Delete
[411] Fix | Delete
def _putline(self, line):
[412] Fix | Delete
"""Internal: send one line to the server, appending CRLF.
[413] Fix | Delete
The `line` must be a bytes-like object."""
[414] Fix | Delete
line = line + _CRLF
[415] Fix | Delete
if self.debugging > 1: print('*put*', repr(line))
[416] Fix | Delete
self.file.write(line)
[417] Fix | Delete
self.file.flush()
[418] Fix | Delete
[419] Fix | Delete
def _putcmd(self, line):
[420] Fix | Delete
"""Internal: send one command to the server (through _putline()).
[421] Fix | Delete
The `line` must be a unicode string."""
[422] Fix | Delete
if self.debugging: print('*cmd*', repr(line))
[423] Fix | Delete
line = line.encode(self.encoding, self.errors)
[424] Fix | Delete
self._putline(line)
[425] Fix | Delete
[426] Fix | Delete
def _getline(self, strip_crlf=True):
[427] Fix | Delete
"""Internal: return one line from the server, stripping _CRLF.
[428] Fix | Delete
Raise EOFError if the connection is closed.
[429] Fix | Delete
Returns a bytes object."""
[430] Fix | Delete
line = self.file.readline(_MAXLINE +1)
[431] Fix | Delete
if len(line) > _MAXLINE:
[432] Fix | Delete
raise NNTPDataError('line too long')
[433] Fix | Delete
if self.debugging > 1:
[434] Fix | Delete
print('*get*', repr(line))
[435] Fix | Delete
if not line: raise EOFError
[436] Fix | Delete
if strip_crlf:
[437] Fix | Delete
if line[-2:] == _CRLF:
[438] Fix | Delete
line = line[:-2]
[439] Fix | Delete
elif line[-1:] in _CRLF:
[440] Fix | Delete
line = line[:-1]
[441] Fix | Delete
return line
[442] Fix | Delete
[443] Fix | Delete
def _getresp(self):
[444] Fix | Delete
"""Internal: get a response from the server.
[445] Fix | Delete
Raise various errors if the response indicates an error.
[446] Fix | Delete
Returns a unicode string."""
[447] Fix | Delete
resp = self._getline()
[448] Fix | Delete
if self.debugging: print('*resp*', repr(resp))
[449] Fix | Delete
resp = resp.decode(self.encoding, self.errors)
[450] Fix | Delete
c = resp[:1]
[451] Fix | Delete
if c == '4':
[452] Fix | Delete
raise NNTPTemporaryError(resp)
[453] Fix | Delete
if c == '5':
[454] Fix | Delete
raise NNTPPermanentError(resp)
[455] Fix | Delete
if c not in '123':
[456] Fix | Delete
raise NNTPProtocolError(resp)
[457] Fix | Delete
return resp
[458] Fix | Delete
[459] Fix | Delete
def _getlongresp(self, file=None):
[460] Fix | Delete
"""Internal: get a response plus following text from the server.
[461] Fix | Delete
Raise various errors if the response indicates an error.
[462] Fix | Delete
[463] Fix | Delete
Returns a (response, lines) tuple where `response` is a unicode
[464] Fix | Delete
string and `lines` is a list of bytes objects.
[465] Fix | Delete
If `file` is a file-like object, it must be open in binary mode.
[466] Fix | Delete
"""
[467] Fix | Delete
[468] Fix | Delete
openedFile = None
[469] Fix | Delete
try:
[470] Fix | Delete
# If a string was passed then open a file with that name
[471] Fix | Delete
if isinstance(file, (str, bytes)):
[472] Fix | Delete
openedFile = file = open(file, "wb")
[473] Fix | Delete
[474] Fix | Delete
resp = self._getresp()
[475] Fix | Delete
if resp[:3] not in _LONGRESP:
[476] Fix | Delete
raise NNTPReplyError(resp)
[477] Fix | Delete
[478] Fix | Delete
lines = []
[479] Fix | Delete
if file is not None:
[480] Fix | Delete
# XXX lines = None instead?
[481] Fix | Delete
terminators = (b'.' + _CRLF, b'.\n')
[482] Fix | Delete
while 1:
[483] Fix | Delete
line = self._getline(False)
[484] Fix | Delete
if line in terminators:
[485] Fix | Delete
break
[486] Fix | Delete
if line.startswith(b'..'):
[487] Fix | Delete
line = line[1:]
[488] Fix | Delete
file.write(line)
[489] Fix | Delete
else:
[490] Fix | Delete
terminator = b'.'
[491] Fix | Delete
while 1:
[492] Fix | Delete
line = self._getline()
[493] Fix | Delete
if line == terminator:
[494] Fix | Delete
break
[495] Fix | Delete
if line.startswith(b'..'):
[496] Fix | Delete
line = line[1:]
[497] Fix | Delete
lines.append(line)
[498] Fix | Delete
finally:
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function