Consolidate message sending into nntp.client.socket, to allow for usage of the same code to send messages to both clients and servers
46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
from nntp.tiny.buffer import OutputBuffer, LineBuffer
|
|
from nntp.tiny.message import Message, MessagePart, each_line
|
|
|
|
class Connection():
|
|
def __init__(self, sock):
|
|
self.sock = sock
|
|
self.output = OutputBuffer(sock)
|
|
self.buf = LineBuffer()
|
|
|
|
def print(self, text: str, end: str="\r\n"):
|
|
return self.output.print(text, end)
|
|
|
|
def flush(self):
|
|
return self.output.flush()
|
|
|
|
def readline(self):
|
|
self.flush()
|
|
return self.buf.readline(self.sock)
|
|
|
|
def end(self):
|
|
return self.print('.')
|
|
|
|
def message_send_headers(self, message: Message):
|
|
for name in message.headers:
|
|
self.print("%s: %s" % (
|
|
name, message.headers[name]
|
|
))
|
|
|
|
def message_send_body(self, body: str):
|
|
for line in each_line(body):
|
|
stripped = line.rstrip()
|
|
|
|
if stripped == '.':
|
|
self.print('..')
|
|
else:
|
|
self.print(stripped)
|
|
|
|
def message_send(self, message: Message, part: MessagePart):
|
|
if part is MessagePart.HEAD or part is MessagePart.WHOLE:
|
|
self.message_send_headers(message)
|
|
|
|
if part is MessagePart.WHOLE:
|
|
self.print('')
|
|
|
|
if part is MessagePart.BODY or part is MessagePart.WHOLE:
|
|
self.message_send_body(message.body)
|