| 297 | |
| 298 | # The classes themselves |
| 299 | class NNTP: |
| 300 | # UTF-8 is the character set for all NNTP commands and responses: they |
| 301 | # are automatically encoded (when sending) and decoded (and receiving) |
| 302 | # by this class. |
| 303 | # However, some multi-line data blocks can contain arbitrary bytes (for |
| 304 | # example, latin-1 or utf-16 data in the body of a message). Commands |
| 305 | # taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message |
| 306 | # data will therefore only accept and produce bytes objects. |
| 307 | # Furthermore, since there could be non-compliant servers out there, |
| 308 | # we use 'surrogateescape' as the error handler for fault tolerance |
| 309 | # and easy round-tripping. This could be useful for some applications |
| 310 | # (e.g. NNTP gateways). |
| 311 | |
| 312 | encoding = 'utf-8' |
| 313 | errors = 'surrogateescape' |
| 314 | |
| 315 | def __init__(self, host, port=NNTP_PORT, user=None, password=None, |
| 316 | readermode=None, usenetrc=False, |
| 317 | timeout=_GLOBAL_DEFAULT_TIMEOUT): |
| 318 | """Initialize an instance. Arguments: |
| 319 | - host: hostname to connect to |
| 320 | - port: port to connect to (default the standard NNTP port) |
| 321 | - user: username to authenticate with |
| 322 | - password: password to use with username |
| 323 | - readermode: if true, send 'mode reader' command after |
| 324 | connecting. |
| 325 | - usenetrc: allow loading username and password from ~/.netrc file |
| 326 | if not specified explicitly |
| 327 | - timeout: timeout (in seconds) used for socket connections |
| 328 | |
| 329 | readermode is sometimes necessary if you are connecting to an |
| 330 | NNTP server on the local machine and intend to call |
| 331 | reader-specific commands, such as `group'. If you get |
| 332 | unexpected NNTPPermanentErrors, you might need to set |
| 333 | readermode. |
| 334 | """ |
| 335 | self.host = host |
| 336 | self.port = port |
| 337 | self.sock = self._create_socket(timeout) |
| 338 | self.file = None |
| 339 | try: |
| 340 | self.file = self.sock.makefile("rwb") |
| 341 | self._base_init(readermode) |
| 342 | if user or usenetrc: |
| 343 | self.login(user, password, usenetrc) |
| 344 | except: |
| 345 | if self.file: |
| 346 | self.file.close() |
| 347 | self.sock.close() |
| 348 | raise |
| 349 | |
| 350 | def _base_init(self, readermode): |
| 351 | """Partial initialization for the NNTP protocol. |
| 352 | This instance method is extracted for supporting the test code. |
| 353 | """ |
| 354 | self.debugging = 0 |
| 355 | self.welcome = self._getresp() |
| 356 | |