2015-10-24 18:12:02 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
import inspect
|
|
|
|
import logging
|
|
|
|
|
2015-10-24 22:20:20 +02:00
|
|
|
import irc
|
|
|
|
|
2015-10-24 19:16:08 +02:00
|
|
|
logging.basicConfig(format="[%(asctime)s] [%(levelname)s] %(message)s", level=logging.DEBUG, datefmt="%d.%m.%Y %H:%M:%S")
|
2015-10-24 18:12:02 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class ManagedProtocol(asyncio.Protocol):
|
|
|
|
"""Basic managed protocol handler, registers itself to ConnectionManager.
|
2015-10-24 19:16:08 +02:00
|
|
|
Inherit this to overlay the management with actual protocol parsing.
|
2015-10-24 18:12:02 +02:00
|
|
|
"""
|
|
|
|
|
2015-10-24 22:20:20 +02:00
|
|
|
def __init__(self, config=None, loop=None, connection_manager=None, endpoint=None):
|
2015-10-24 18:12:02 +02:00
|
|
|
self._loop = loop
|
|
|
|
self._connection_manager = connection_manager
|
|
|
|
self._endpoint = endpoint
|
|
|
|
self._transport = None
|
2015-10-24 22:20:20 +02:00
|
|
|
self._config = config
|
2015-10-24 18:12:02 +02:00
|
|
|
|
2015-10-25 12:51:17 +01:00
|
|
|
def log(self, msg):
|
2015-10-24 18:12:02 +02:00
|
|
|
host, port = self._endpoint
|
|
|
|
logger.info("[{}:{}] ".format(host, port)+str(msg))
|
|
|
|
|
|
|
|
def connection_made(self, transport):
|
|
|
|
self._connection_manager.register_active_connection(self._endpoint, self)
|
|
|
|
self._transport = transport
|
2015-10-25 12:51:17 +01:00
|
|
|
self.log("Connection made!")
|
2015-10-24 19:16:08 +02:00
|
|
|
host, port = transport.get_extra_info("peername")
|
2015-10-25 12:51:17 +01:00
|
|
|
self.log("Connected to: {}:{}".format(host, port))
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
def data_received(self, data):
|
2015-10-25 12:51:17 +01:00
|
|
|
#self.log("[R] "+str(data))
|
2015-10-25 00:51:57 +02:00
|
|
|
pass
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
def eof_received(self):
|
2015-10-25 12:51:17 +01:00
|
|
|
self.log("Eof received!")
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
def connection_lost(self, exc):
|
2015-10-25 12:51:17 +01:00
|
|
|
self.log("Connection lost! ("+str(exc)+")")
|
2015-10-24 18:12:02 +02:00
|
|
|
self._connection_manager.unregister_active_connection(self._endpoint)
|
|
|
|
|
2015-10-24 19:16:08 +02:00
|
|
|
def send_data(self, data):
|
2015-10-25 12:51:17 +01:00
|
|
|
#self.log("[W] "+str(data))
|
2015-10-24 19:16:08 +02:00
|
|
|
self._transport.write(data)
|
|
|
|
|
2015-10-24 18:12:02 +02:00
|
|
|
def destroy(self):
|
|
|
|
""" Triggered by ConnectionManager.remove_endpoint(). Closes transport. """
|
|
|
|
self._transport.close()
|
|
|
|
|
2015-10-24 22:20:20 +02:00
|
|
|
def get_config(self):
|
|
|
|
return self._config
|
2015-10-24 18:12:02 +02:00
|
|
|
|
2015-10-25 01:13:15 +02:00
|
|
|
|
2015-10-24 18:12:02 +02:00
|
|
|
class IrcProtocol(ManagedProtocol):
|
2015-10-24 19:16:08 +02:00
|
|
|
"""Implementation of the IRC protocol.
|
|
|
|
"""
|
|
|
|
|
2015-10-24 22:20:20 +02:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(IrcProtocol, self).__init__(*args, **kwargs)
|
2015-10-24 19:16:08 +02:00
|
|
|
self.motd = False
|
|
|
|
self.hello = False
|
2015-10-24 22:20:20 +02:00
|
|
|
self._config = self.get_config()
|
|
|
|
self._buffer = b""
|
|
|
|
|
|
|
|
def encode(self, str):
|
|
|
|
return str.encode(self._config["encoding"], "replace")
|
|
|
|
|
|
|
|
def decode(self, bytes):
|
|
|
|
return bytes.decode(self._config["encoding"], "replace")
|
2015-10-24 19:16:08 +02:00
|
|
|
|
|
|
|
def connection_made(self, transport):
|
|
|
|
super(IrcProtocol, self).connection_made(transport)
|
2015-10-24 23:55:08 +02:00
|
|
|
self.send_msg(irc.User(self._config["ident"], self._config["realname"]))
|
|
|
|
self.send_msg(irc.Nick(self._config["nick"]))
|
2015-10-25 12:21:47 +01:00
|
|
|
self.nick = self._config["nick"]
|
2015-10-24 18:12:02 +02:00
|
|
|
|
2015-10-24 19:16:08 +02:00
|
|
|
def data_received(self, data):
|
|
|
|
super(IrcProtocol, self).data_received(data)
|
2015-10-24 22:20:20 +02:00
|
|
|
self._buffer += data
|
|
|
|
self.process_data()
|
2015-10-24 19:16:08 +02:00
|
|
|
|
2015-10-24 22:20:20 +02:00
|
|
|
def process_data(self):
|
2015-10-24 22:27:08 +02:00
|
|
|
while b"\r\n" in self._buffer:
|
|
|
|
line, self._buffer = self._buffer.split(b"\r\n", 1)
|
2015-10-24 22:20:20 +02:00
|
|
|
line = self.decode(line.strip())
|
2015-10-25 00:51:57 +02:00
|
|
|
if line == "":
|
|
|
|
continue
|
2015-10-24 23:55:08 +02:00
|
|
|
msg = irc.Message.from_string(line)
|
|
|
|
self.msg_received(msg)
|
2015-10-24 19:16:08 +02:00
|
|
|
|
2015-10-24 23:55:08 +02:00
|
|
|
def send_msg(self, msg):
|
|
|
|
if isinstance(msg, irc.Message):
|
2015-10-25 12:51:17 +01:00
|
|
|
self.log(msg.__repr__())
|
2015-10-25 00:51:57 +02:00
|
|
|
data = self.encode(str(msg)+"\r\n")
|
2015-10-24 23:55:08 +02:00
|
|
|
self.send_data(data)
|
|
|
|
|
|
|
|
def msg_received(self, msg):
|
2015-10-25 12:51:17 +01:00
|
|
|
self.log(msg.__repr__())
|
2015-10-24 23:55:08 +02:00
|
|
|
if isinstance(msg, irc.Ping):
|
|
|
|
self.send_msg(irc.Pong(msg))
|
|
|
|
if isinstance(msg, irc.Message) and msg.get('command') == "376":
|
|
|
|
self.ready()
|
2015-10-25 00:51:57 +02:00
|
|
|
if isinstance(msg, irc.Privmsg):
|
|
|
|
if msg.message == "-cycle":
|
|
|
|
self.send_msg(irc.Part(msg.target, "Hop!"))
|
|
|
|
self.send_msg(irc.Join(msg.target))
|
2015-10-25 01:13:15 +02:00
|
|
|
if isinstance(msg, irc.Privmsg):
|
|
|
|
if msg.message.startswith("\x01") and msg.message.endswith("\x01"):
|
|
|
|
text = msg.message.strip("\x01")
|
|
|
|
if text.upper() == "VERSION":
|
2015-10-25 12:12:11 +01:00
|
|
|
self.send_msg(irc.Privmsg(msg.get("nick"), "\x01HalloWelt lustiger Client v0.0.1\x01"))
|
2015-10-25 12:21:47 +01:00
|
|
|
if isinstance(msg, irc.Kick):
|
|
|
|
if msg.target == self.nick:
|
|
|
|
self.send_msg(irc.Join(msg.channel))
|
|
|
|
self.send_msg(irc.Privmsg(msg.channel, "Hey, das war nicht nett!"))
|
2015-10-24 23:55:08 +02:00
|
|
|
|
|
|
|
def ready(self):
|
|
|
|
for channel in self._config["channels"]:
|
|
|
|
self.send_msg(irc.Join(channel))
|
|
|
|
self.send_msg(irc.Privmsg(channel, "Hallo Welt!"))
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
class ConnectionManager(object):
|
|
|
|
"""Takes care of known endpoints that a connections shall be established to.
|
2015-10-24 22:20:20 +02:00
|
|
|
Stores configurations for every configuration.
|
2015-10-24 18:12:02 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, loop):
|
|
|
|
self._loop = loop
|
|
|
|
self._endpoints = []
|
2015-10-24 22:20:20 +02:00
|
|
|
self._configs = {}
|
2015-10-24 18:12:02 +02:00
|
|
|
self._active_connections = {}
|
|
|
|
self._loop.set_exception_handler(self._handle_async_exception)
|
|
|
|
|
2015-10-24 22:20:20 +02:00
|
|
|
def add_endpoint(self, endpoint, config):
|
2015-10-24 18:40:52 +02:00
|
|
|
logger.debug("Endpoint added: {}:{}".format(*endpoint))
|
2015-10-24 18:12:02 +02:00
|
|
|
self._endpoints.append(endpoint)
|
2015-10-24 22:20:20 +02:00
|
|
|
self._configs[endpoint] = config
|
2015-10-24 18:12:02 +02:00
|
|
|
self._create_connection(endpoint)
|
|
|
|
|
|
|
|
def _create_connection(self, endpoint):
|
2015-10-24 22:20:20 +02:00
|
|
|
protocol = IrcProtocol(config=self._configs[endpoint], loop=self._loop, connection_manager=self, endpoint=endpoint)
|
2015-10-24 18:40:52 +02:00
|
|
|
coroutine = self._loop.create_connection(lambda: protocol, *endpoint)
|
2015-10-24 22:20:20 +02:00
|
|
|
asyncio.ensure_future(coroutine)
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
def remove_endpoint(self, endpoint):
|
2015-10-24 18:40:52 +02:00
|
|
|
logger.debug("Endpoint removed: {}:{}".format(*endpoint))
|
2015-10-24 18:12:02 +02:00
|
|
|
self._endpoints.remove(endpoint)
|
2015-10-24 22:20:20 +02:00
|
|
|
del self._configs[endpoint]
|
2015-10-24 18:12:02 +02:00
|
|
|
if endpoint in self._active_connections:
|
|
|
|
self._active_connections[endpoint].close()
|
|
|
|
|
|
|
|
def register_active_connection(self, endpoint, protocol):
|
|
|
|
self._active_connections[endpoint] = protocol
|
|
|
|
|
|
|
|
def unregister_active_connection(self, endpoint):
|
|
|
|
del self._active_connections[endpoint]
|
|
|
|
self._create_connection(endpoint)
|
|
|
|
|
|
|
|
def _handle_async_exception(self, loop, context):
|
|
|
|
"""Trying to take care of connection related exceptions."""
|
2015-10-24 19:16:08 +02:00
|
|
|
logger.error("An async exception has been caught: "+str(context["exception"]))
|
|
|
|
stack = context["future"].get_stack()
|
|
|
|
if len(stack) > 1 and stack[1].f_code.co_name == "create_connection":
|
2015-10-24 18:12:02 +02:00
|
|
|
last_stackframe = stack[len(stack)-1]
|
|
|
|
call_args = inspect.getargvalues(last_stackframe)
|
2015-10-24 19:16:08 +02:00
|
|
|
host = call_args.locals["host"]
|
|
|
|
port = call_args.locals["port"]
|
2015-10-24 18:12:02 +02:00
|
|
|
logger.error("Bad endpoint: {}:{}".format(host, port))
|
|
|
|
self.remove_endpoint((host, port))
|
2015-10-24 18:40:52 +02:00
|
|
|
else:
|
|
|
|
loop.call_exception_handler(context)
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
|
2015-10-24 19:16:08 +02:00
|
|
|
if __name__ == "__main__":
|
2015-10-24 18:12:02 +02:00
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
|
|
|
|
connection_manager = ConnectionManager(loop)
|
2015-10-24 23:05:55 +02:00
|
|
|
connection_manager.add_endpoint(("irc.euirc.net", 6667), {
|
2015-10-24 22:20:20 +02:00
|
|
|
"encoding": "utf-8",
|
|
|
|
"nick": "Pb42",
|
2015-10-24 23:55:08 +02:00
|
|
|
"ident": "foobar2000",
|
2015-10-24 22:20:20 +02:00
|
|
|
"realname": "Baz McBatzen",
|
|
|
|
"channels": ["#botted"]
|
|
|
|
})
|
2015-10-25 13:10:21 +01:00
|
|
|
connection_manager.add_endpoint(("irc.freenode.net", 6667), {
|
|
|
|
"encoding": "utf-8",
|
|
|
|
"nick": "Pb42",
|
|
|
|
"ident": "foobar2000",
|
|
|
|
"realname": "Baz McBatzen",
|
|
|
|
"channels": ["#botted"]
|
|
|
|
})
|
2015-10-24 18:12:02 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
loop.run_forever()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
loop.close()
|