1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
#!/usr/bin/env python
import sys, time, yaml, os, json
from twisted.internet import reactor, protocol, task
#from twisted.internet import endpoints
from twisted.web import server, resource, static
from twisted.words.protocols import irc
from twisted.python import log
from crontab import CronTab
config_file = "config.yaml"
midnight = CronTab("0 0 * * *")
log.startLogging(sys.stdout)
class Config(object):
_cfg = None
_file = config_file
def __init__(self):
with open(self._file, 'r') as fp:
self._cfg = yaml.load(fp)
log.msg("Loaded config from file")
def save(self):
with open(self._file, 'w') as fp:
yaml.dump(self.cfg, fp)
log.msg("Dumped config to file")
@property
def cfg(self):
return self._cfg
@cfg.setter
def cfg(self, newCfg):
self._cfg = newCfg
self.save()
config = Config()
class Cache(object):
_cache = {}
_file = config.cfg.get("cache").get("file")
_max_log = config.cfg.get("cache").get("max_log")
_changed = False
def __init__(self):
if os.path.exists(self._file):
with open(self._file, 'r') as fp:
tmp = yaml.load(fp)
self._cache = tmp
log.msg("Loaded cache from file")
def setTopic(self, newTopic, channel):
if self._cache[channel]["topic"] != newTopic:
self._cache[channel]["topic"] = newTopic
self._changed = True
def addMsg(self, msg, channel):
if channel != None:
self._cache[channel]["msg"].append(msg)
self._changed = True
while len(self._cache[channel]["msg"]) > self._max_log:
self._cache[channel]["msg"].pop(0)
else:
for channel in self._cache:
self._cache[channel]["msg"].append(msg)
self._changed = True
while len(self._cache[channel]["msg"]) > self._max_log:
self._cache[channel]["msg"].pop(0)
def addChannel(self, channel):
if self._cache.get(channel, None) == None:
self._cache[channel] = {}
self._changed = True
if self._cache[channel].get("topic", None) == None:
self._cache[channel]["topic"] = ""
self._changed = True
if self._cache[channel].get("msg", None) == None:
self._cache[channel]["msg"] = []
self._changed = True
@property
def cache(self):
return self._cache
def save(self):
if self._changed:
with open(self._file, 'w') as fp:
yaml.dump(self._cache, fp)
log.msg("Dumped cache to file")
self._changed = False
cache = Cache()
class Root(resource.Resource):
def getChild(self, path, request):
if path == '':
return static.File("index.html")
return resource.Resource.getChild(self, path, request)
def render_GET(self, request):
log.msg(request)
class Subscribe(resource.Resource):
isLeaf = True
def __init__(self):
self.subscribers = set()
def render_GET(self, request):
request.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
request.setResponseCode(200)
self.subscribers.add(request)
channel = request.uri.split("?", 1)
if len(channel) != 2:
channel = None
else:
channel = "#%s" % channel[-1]
request.channel = channel
d = request.notifyFinish()
d.addBoth(self.removeSubscriber)
log.msg("Adding subscriber...")
request.write("")
return server.NOT_DONE_YET
def removeSubscriber(self, subscriber):
if subscriber in self.subscribers:
log.msg("Removing subscriber")
self.subscribers.remove(subscriber)
def publishToAll(self, data, channel=None):
for subscriber in self.subscribers:
if subscriber.channel == channel or channel == None:
for line in data.split('\n'):
subscriber.write("data: %s\n" % line)
subscriber.write("\n")
subscribe = Subscribe()
class Backlog(resource.Resource):
isLeaf = True
def render_GET(self, request):
channel = request.uri.split("?", 1)
if len(channel) != 2:
channel = None
else:
channel = channel[-1]
return json.dumps(cache.cache.get("#%s" % channel, {}))
class IRCBotProtocol(irc.IRCClient):
admins = config.cfg.get("irc").get("admins")
nickname = config.cfg.get("irc").get("nick")
def connectionMade(self):
irc.IRCClient.connectionMade(self)
log.msg("Connected to IRC")
def signedOn(self):
for channel in config.cfg.get("irc").get("channels"):
log.msg("Joining %s" % channel)
self.join(channel)
def joined(self, channel):
log.msg("Joined %s" % channel)
cache.addChannel(channel)
#self.topic(channel, None)
def topicUpdated(self, user, channel, newTopic):
if channel == self.nickname:
return
msg = {
"type": "topic",
"user": user,
"channel": channel,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
"topic": newTopic,
}
#log.msg("%s %s Topic %s" % (user, channel, newTopic))
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.setTopic(newTopic, channel)
cache.addMsg(msg, channel)
def privmsg(self, user, channel, message):
if channel == self.nickname:
if message == "!refresh" and user in self.admins:
subscribe.publishToAll("%s" % json.dumps({"type":"refresh"}), None)
return
msg = {
"type": "privmsg",
"user": user,
"channel": channel,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
"message": message,
}
log.msg("%s %s %s" % (user, channel, message))
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.addMsg(msg, channel)
def action(self, user, channel, action):
if channel == self.nickname:
return
msg = {
"type": "action",
"user": user,
"channel": channel,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
"action": action,
}
#log.msg("%s %s %s" % (user, channel, action))
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.addMsg(msg, channel)
def modeChanged(self, user, channel, set, modes, args):
if channel == self.nickname:
return
#log.msg("%s\n%s\n%s\n%s\n%s" % (user, channel, set, modes, list(args)))
msg = {
"type": "mode",
"user": user,
"channel": channel,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
"set": set,
"modes": modes,
"args": list(args),
}
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.addMsg(msg, channel)
def userLeft(self, user, channel):
### Keep track of users
if channel == self.nickname:
return
msg = {
"type": "leave",
"user": user,
"channel": channel,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
}
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.addMsg(msg, channel)
def userJoined(self, user, channel):
### Keep track of users
if channel == self.nickname:
return
msg = {
"type": "join",
"user": user,
"channel": channel,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
}
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.addMsg(msg, channel)
def userQuit(self, user, quitMessage):
### We need to keep track of names if we want to use this...
return
def userKicked(self, kickee, channel, kicker, message):
### Keep track of users
msg = {
"type": "kick",
"kickee": kickee,
"channel": channel,
"kicker": kicker,
"message": message,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
}
subscribe.publishToAll("%s" % json.dumps(msg), channel)
cache.addMsg(msg, channel)
def userRenamed(self, oldname, newname):
### We might need to keep track of users here to... :(
msg = {
"type": "rename",
"oldname": oldname,
"newname": newname,
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
}
subscribe.publishToAll("%s" % json.dumps(msg), None)
cache.addMsg(msg, None)
def alterCollideNick(self, nick):
return nick + "^"
class IRCBotFactory(protocol.ClientFactory):
protocol = IRCBotProtocol
def day_change():
reactor.callLater(midnight.next(), day_change)
msg = {
"type": "daychange",
"time": time.strftime("%H:%M:%S", time.localtime(time.time())),
"date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
}
log.msg("Day changed...")
cache.addMsg(msg, None)
subscribe.publishToAll("%s" % json.dumps(msg), None)
root = Root()
root.putChild("subscribe", subscribe)
root.putChild("backlog", Backlog())
root.putChild("style.css", static.File("style.css"))
root.putChild("irc-sse.js", static.File("irc-sse.js"))
site = server.Site(root)
t = task.LoopingCall(cache.save)
t.start(30)
reactor.callLater(midnight.next(), day_change)
reactor.addSystemEventTrigger("after", "shutdown", cache.save)
reactor.listenTCP(config.cfg.get("http").get("port"), site)
reactor.connectTCP(config.cfg.get("irc").get("server"), config.cfg.get("irc").get("port"), IRCBotFactory())
reactor.run()
|