This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
/
ircviewer.py
executable file
·303 lines (241 loc) · 9.23 KB
/
ircviewer.py
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
#!/usr/bin/env python
import sys
try:
import json
except ImportError:
import simplejson as json
from optparse import OptionParser
import time
import logging
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor
from twisted.web.server import Site
from twisted.web import server, http
from twisted.web.resource import Resource
from twisted.web.static import File
from twisted.web.error import NoResource
auth_user = auth_password = None
def setup_logger(logger):
console_handler = logging.StreamHandler()
format = "[%(levelname)s] - %(asctime)s - %(message)s"
console_handler.setFormatter(logging.Formatter(format))
logger.addHandler(console_handler)
class LogBot(irc.IRCClient):
"""IRC bot that sends updates to the web handler.
"""
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def signedOn(self):
self.join(self.factory.channel)
logger.info("Connected to server as %s" % self.nickname)
def joined(self, channel):
logger.info("Joined channel %s" % channel)
def privmsg(self, user, channel, message):
logger.info("Message from %s: %s" % (user.split('!')[0], message))
action = {
'command': 'privmsg',
'user': user,
'message': message,
'timestamp': int(time.time()),
}
self.factory.add_to_history(action)
self.factory.web_resource.update(action)
def userJoined(self, user, channel):
logger.info("%s joined" % user.split('!')[0])
action = {
'command': 'userjoined',
'user': user,
'timestamp': int(time.time()),
}
self.factory.add_to_history(action)
self.factory.web_resource.update(action)
def userLeft(self, user, channel):
logger.info("%s left" % user.split('!')[0])
action = {
'command': 'userleft',
'user': user,
'timestamp': int(time.time()),
}
self.factory.add_to_history(action)
self.factory.web_resource.update(action)
def userQuit(self, user, message):
logger.info("%s quit" % user.split('!')[0])
action = {
'command': 'userquit',
'user': user,
'timestamp': int(time.time()),
}
self.factory.add_to_history(action)
self.factory.web_resource.update(action)
class LogBotFactory(protocol.ClientFactory):
protocol = LogBot
def __init__(self, channel, web_resource, nickname='LogBot',
history_file='irc-history.log', history_cache_size=500):
self.channel = channel
self.web_resource = web_resource
self.nickname = nickname
self.history_file = history_file
self.history_cache_size = history_cache_size
self.history = self.load_history()
def load_history(self):
"""Load history from a JSON history file, where each line should be
valid JSON and correspond to a single action.
"""
history = []
try:
for line in open(self.history_file):
history.append(line)
# Ensure that we're not loading more than is necessary
if len(history) > self.history_cache_size:
history.pop(0)
# Convert the JSON strings to actions (dicts)
history = [json.loads(line) for line in history]
except:
pass
return history
def add_to_history(self, action):
"""Add an item to the history, this will also be saved to disk.
"""
self.history.append(action)
while len(self.history) > self.history_cache_size:
self.history.pop(0)
open(self.history_file, 'a').write(json.dumps(action) + '\n')
def clientConnectionLost(self, connector, reason):
logger.warn("Lost connection (%s)" % reason.getErrorMessage())
logger.warn("Reconnecting to server...")
connector.connect()
def clientConnectionFailed(self, connector, reason):
logger.error("Could not connect (%s)" % reason.getErrorMessage())
sys.exit(1)
def escape_html(text):
"""Produce entities within text."""
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
return "".join(html_escape_table.get(c,c) for c in text)
def authenticate(func):
"""Decorator to restrict access to pages to authenticated clients.
"""
def auth_func(self, request, *args, **kwargs):
user = request.getUser()
password = request.getPassword()
if auth_user and auth_password:
if user != auth_user or password != auth_password:
request.setResponseCode(http.UNAUTHORIZED)
realm = 'basic realm="IRC Viewer"'
request.setHeader('WWW-authenticate', realm)
return ''
return func(self, request, *args, **kwargs)
return auth_func
def prepare_action(action):
"""Prepare an action for sending to the client - escape quotes, etc.
"""
action = action.copy()
# Select only the *name* part of the user's name
if 'user' in action:
action['user'] = action['user'].split('!')[0]
for key, value in action.items():
if isinstance(key, basestring):
key = escape_html(key)
if isinstance(value, basestring):
value = escape_html(value)
action[key] = value
return action
class IrcLogUpdate(Resource):
"""A Twisted web resource that uses long-polling to send IRC updates to
clients as JSON.
"""
isLeaf = True
def __init__(self):
self.clients = []
Resource.__init__(self)
@authenticate
def render_GET(self, request):
request.setHeader('Content-Type', 'application/json')
# Add the client to the client list; the response will be returned when
# a new action occurs
self.clients.append(request)
request.notifyFinish().addErrback(self.lost_client, request)
return server.NOT_DONE_YET
def lost_client(self, err, client):
"""Remove the client in the event of a disconnect or error.
"""
if client in self.clients:
self.clients.remove(client)
def update(self, action):
"""Update all waiting clients with a new action.
"""
payload = json.dumps(prepare_action(action))
clients = self.clients[:]
self.clients = []
for client in clients:
client.write(payload)
client.finish()
class IrcLogHistory(Resource):
"""A Twisted web resource that returns IRC history as JSON.
"""
isLeaf = True
def __init__(self, log_bot_factory):
self.log_bot_factory = log_bot_factory
@authenticate
def render_GET(self, request):
request.setHeader('Content-Type', 'application/json')
history = []
for action in self.log_bot_factory.history:
history.append(prepare_action(action))
return json.dumps(history)
# Set up logging
logger = logging.getLogger('ircviewer')
setup_logger(logger)
def main():
usage = 'usage: %prog [options] irc_host[:port] channel'
parser = OptionParser(usage)
parser.add_option('-p', '--port', help='Port to run the HTTP server on',
default=8080, type='int')
parser.add_option('-n', '--nick', help='IRC bot nickname', type='str',
default='IRCViewer')
parser.add_option('-a', '--auth', help='Authentication (user:password)',
type='str')
options, args = parser.parse_args()
# Parse the connection string with format host[:port]
try:
irc_host, irc_port = args[0], 6667
if ':' in irc_host:
irc_host, irc_port = args[0].split(':')
irc_port = int(irc_port)
except:
parser.error('invalid IRC host/port, use format hostname[:port]')
# Ensure the channel is present
try:
channel = '#' + args[1].strip('#')
except:
parser.error('invalid or missing IRC channel')
# Set up authentication details if provided
if options.auth is not None:
if len(options.auth.split(':')) != 2:
parser.error("invalid auth details, use format user:password")
auth_user, auth_password = options.auth.split(':')
if not auth_user or not auth_password:
parser.error("invalid auth details, use format user:password")
logger.setLevel(logging.INFO)
# Set up the web resources for displaying the logs
web_resource = Resource()
update_web_resource = IrcLogUpdate()
web_resource.putChild("", File('main.html'))
web_resource.putChild("update.js", update_web_resource)
web_resource.putChild("static", File("static"))
web_factory = Site(web_resource)
reactor.listenTCP(options.port, web_factory)
log_bot_factory = LogBotFactory(channel, update_web_resource,
nickname=options.nick)
reactor.connectTCP(irc_host, irc_port, log_bot_factory)
web_resource.putChild("history.js", IrcLogHistory(log_bot_factory))
logger.info('Starting HTTP server on port %d' % options.port)
reactor.run()
if __name__ == '__main__':
main()