]> jfr.im git - irc/quakenet/qwebirc.git/blob - qwebirc/ircclient.py
Dos2Unix
[irc/quakenet/qwebirc.git] / qwebirc / ircclient.py
1 import twisted, sys
2 from twisted.words.protocols import irc
3 from twisted.internet import reactor, protocol
4 from twisted.web import resource, server
5 from twisted.protocols import basic
6
7 import hmac, time, config
8 from config import HMACTEMPORAL
9 HMACKEY = hmac.HMAC(key=config.HMACKEY)
10
11 def hmacfn(*args):
12 h = HMACKEY.copy()
13 h.update("%d %s" % (int(time.time() / HMACTEMPORAL), " ".join(args)))
14 return h.hexdigest()
15
16 class QWebIRCClient(basic.LineReceiver):
17 delimiter = "\n"
18
19 def dataReceived(self, data):
20 basic.LineReceiver.dataReceived(self, data.replace("\r", ""))
21
22 def lineReceived(self, line):
23 line = irc.lowDequote(line)
24 try:
25 line = line.decode("utf-8")
26 except UnicodeDecodeError:
27 line = line.decode("iso-8859-1", "ignore")
28
29 try:
30 prefix, command, params = irc.parsemsg(line)
31 self.handleCommand(command, prefix, params)
32 except irc.IRCBadMessage:
33 self.badMessage(line, *sys.exc_info())
34
35 def badMessage(self, args):
36 self("badmessage", args)
37
38 def handleCommand(self, command, prefix, params):
39 self("c", command, prefix, params)
40
41 def __call__(self, *args):
42 self.factory.publisher.event(args)
43
44 def write(self, data):
45 self.transport.write("%s\r\n" % irc.lowQuote(data.encode("utf-8")))
46
47 def connectionMade(self):
48 basic.LineReceiver.connectionMade(self)
49
50 f = self.factory.ircinit
51 nick, ident, ip, realname = f["nick"], f["ident"], f["ip"], f["realname"]
52
53 hmac = hmacfn(ident, ip)
54 self.write("USER %s bleh bleh %s %s :%s" % (ident, ip, hmac, realname))
55 self.write("NICK %s" % nick)
56
57 self.factory.client = self
58 self("connect")
59
60 def connectionLost(self, reason):
61 self.factory.client = None
62 basic.LineReceiver.connectionLost(self, reason)
63 self("disconnect")
64
65 class QWebIRCFactory(protocol.ClientFactory):
66 protocol = QWebIRCClient
67 def __init__(self, publisher, **kwargs):
68 self.client = None
69 self.publisher = publisher
70 self.ircinit = kwargs
71
72 def write(self, data):
73 self.client.write(data)
74
75 def createIRC(*args, **kwargs):
76 f = QWebIRCFactory(*args, **kwargs)
77 reactor.connectTCP(config.IRCSERVER, config.IRCPORT, f)
78 return f
79
80 if __name__ == "__main__":
81 e = createIRC(lambda x: 2, nick="slug__moo", ident="mooslug", ip="1.2.3.6", realname="mooooo")
82 reactor.run()