| 1 |
""" |
| 2 |
Convert IRC logs to HTML. |
| 3 |
|
| 4 |
Usage: irclog2html.py filename |
| 5 |
|
| 6 |
irclog2html will write out a colourised irc log, appending a .html |
| 7 |
extension to the output file. |
| 8 |
|
| 9 |
This is a Python port (+ improvements) of irclog2html.pl Version 2.1, which |
| 10 |
was written by Jeff Waugh and is available at www.perkypants.org |
| 11 |
""" |
| 12 |
|
| 13 |
# Copyright (c) 2005--2014, Marius Gedminas |
| 14 |
# Copyright (c) 2000, Jeffrey W. Waugh |
| 15 |
|
| 16 |
# Python port: |
| 17 |
# Marius Gedminas <[email protected]> |
| 18 |
# Original Author: |
| 19 |
# Jeff Waugh <[email protected]> |
| 20 |
# Contributors: |
| 21 |
# Rick Welykochy <[email protected]> |
| 22 |
# Alexander Else <[email protected]> |
| 23 |
# Ian Weller <[email protected]> |
| 24 |
# |
| 25 |
# Released under the terms of the GNU GPL |
| 26 |
# https://www.gnu.org/copyleft/gpl.html |
| 27 |
|
| 28 |
# Differences from the Perl version: |
| 29 |
# There are no hardcoded nick colour preferences for jdub, cantanker and |
| 30 |
# chuckd |
| 31 |
# |
| 32 |
# Colours are preserver accross nick changes (irclog2html.pl tries to do |
| 33 |
# that, but its regexes are buggy) |
| 34 |
# |
| 35 |
# irclog2html.pl interprets --colour-server #rrggbb as -s #rrggbb, |
| 36 |
# irclog2html.py does not have this bug |
| 37 |
# |
| 38 |
# irclog2html.py understands ISO 8601 timestamps (YYYY-MM-DDTHH:MM:SS) |
| 39 |
# |
| 40 |
# New options: --title, --{prev,index,next}-{url,title} and many more |
| 41 |
# |
| 42 |
# New styles: xhtml, xhtmltable, mediawiki |
| 43 |
# |
| 44 |
# New default style: xhtmltable |
| 45 |
# |
| 46 |
|
| 47 |
import datetime |
| 48 |
import gzip |
| 49 |
import io |
| 50 |
import itertools |
| 51 |
import optparse |
| 52 |
import os |
| 53 |
import os.path |
| 54 |
import re |
| 55 |
import shlex |
| 56 |
import shutil |
| 57 |
import sys |
| 58 |
from urllib.parse import quote |
| 59 |
|
| 60 |
from ._version import __date__ as RELEASE |
| 61 |
from ._version import __homepage__ as HOMEPAGE |
| 62 |
from ._version import __version__ as VERSION |
| 63 |
|
| 64 |
|
| 65 |
# If someone packages this for a Linux distro, they'll want to patch this to |
| 66 |
# something like /usr/share/irclog2html/irclog.css, I imagine |
| 67 |
CSS_FILE = os.path.join(os.path.dirname(__file__), 'irclog.css') |
| 68 |
|
| 69 |
|
| 70 |
# |
| 71 |
# Log parsing |
| 72 |
# |
| 73 |
|
| 74 |
class Enum(object): |
| 75 |
"""Enumerated value.""" |
| 76 |
|
| 77 |
def __init__(self, value): |
| 78 |
self.value = value |
| 79 |
|
| 80 |
def __repr__(self): |
| 81 |
return self.value |
| 82 |
|
| 83 |
|
| 84 |
class LogParser(object): |
| 85 |
"""Parse an IRC log file. |
| 86 |
|
| 87 |
When iterated, yields the following events: |
| 88 |
|
| 89 |
time, COMMENT, (nick, text) |
| 90 |
time, ACTION, text |
| 91 |
time, JOIN, text |
| 92 |
time, PART, text, |
| 93 |
time, NICKCHANGE, (text, oldnick, newnick) |
| 94 |
time, SERVER, text |
| 95 |
|
| 96 |
Text is a pure ASCII or Unicode string. |
| 97 |
""" |
| 98 |
|
| 99 |
COMMENT = Enum('COMMENT') |
| 100 |
ACTION = Enum('ACTION') |
| 101 |
JOIN = Enum('JOIN') |
| 102 |
PART = Enum('PART') |
| 103 |
NICKCHANGE = Enum('NICKCHANGE') |
| 104 |
SERVER = Enum('SERVER') |
| 105 |
OTHER = Enum('OTHER') |
| 106 |
|
| 107 |
TIME_REGEXP = re.compile( |
| 108 |
r'^\[?(' # Optional [ |
| 109 |
r'(?:\d{4}-\d{2}-\d{2}T|\d{2}-\w{3}-\d{4} |\w{3} \d{2} |\d{2} \w{3} )?' # Optional date |
| 110 |
r'\d\d:\d\d(:\d\d)?' # Mandatory HH:MM, optional :SS |
| 111 |
r')\]? +') # Optional ], mandatory space |
| 112 |
TIMESTAMP_REGEXP = re.compile(r'^(\d+) +') |
| 113 |
NICK_REGEXP = re.compile(r'^<(.*?)(!.*?)?>\s') |
| 114 |
DIRCPROXY_NICK_REGEXP = re.compile(r'^<(.*?)(!.*)?>\s[\+-]?') |
| 115 |
JOIN_REGEXP = re.compile(r'^(?:\*\*\*|-->|-!-)\s.*joined') |
| 116 |
PART_REGEXP = re.compile(r'^(?:\*\*\*|<--|-!-)\s.*(quit|left)') |
| 117 |
SERVMSG_REGEXP = re.compile(r'^(?:\*\*\*|---|-!-)\s') |
| 118 |
NICK_CHANGE_REGEXP = re.compile( |
| 119 |
r'^(?:\*\*\*|---|-!-)\s+(.*?) (?:are|is) now known as (.*)') |
| 120 |
|
| 121 |
def __init__(self, infile, dircproxy=False): |
| 122 |
self.infile = infile |
| 123 |
if dircproxy: |
| 124 |
self.NICK_REGEXP = self.DIRCPROXY_NICK_REGEXP |
| 125 |
|
| 126 |
@staticmethod |
| 127 |
def decode(s): |
| 128 |
"""Convert 8-bit string to Unicode. |
| 129 |
|
| 130 |
Supports xchat's hybrid Latin/Unicode encoding, as documented here: |
| 131 |
http://xchat.org/encoding/ |
| 132 |
""" |
| 133 |
if isinstance(s, str): |
| 134 |
# Accept input that's already Unicode, for convenience |
| 135 |
return s |
| 136 |
try: |
| 137 |
return s.decode('UTF-8') |
| 138 |
except UnicodeError: |
| 139 |
return s.decode('cp1252', 'replace') |
| 140 |
|
| 141 |
def __iter__(self): |
| 142 |
for line in self.infile: |
| 143 |
line = self.decode(line).rstrip('\r\n') |
| 144 |
if not line: |
| 145 |
continue |
| 146 |
|
| 147 |
m = self.TIME_REGEXP.match(line) |
| 148 |
if m: |
| 149 |
time = m.group(1) |
| 150 |
line = line[len(m.group(0)):] |
| 151 |
else: |
| 152 |
time = None |
| 153 |
|
| 154 |
if time is None: |
| 155 |
m = self.TIMESTAMP_REGEXP.match(line) |
| 156 |
if m: |
| 157 |
time = datetime.datetime.fromtimestamp( |
| 158 |
int(m.group(1)), datetime.timezone.utc |
| 159 |
).strftime('%Y-%m-%dT%H:%M:%S') |
| 160 |
line = line[len(m.group(0)):] |
| 161 |
|
| 162 |
m = self.NICK_REGEXP.match(line) |
| 163 |
if m: |
| 164 |
nick = m.group(1) |
| 165 |
text = line[len(m.group(0)):] |
| 166 |
yield time, self.COMMENT, (nick, text) |
| 167 |
elif line.startswith('* ') or line.startswith('*\t'): |
| 168 |
yield time, self.ACTION, line |
| 169 |
elif self.JOIN_REGEXP.match(line): |
| 170 |
yield time, self.JOIN, line |
| 171 |
elif self.PART_REGEXP.match(line): |
| 172 |
yield time, self.PART, line |
| 173 |
else: |
| 174 |
m = self.NICK_CHANGE_REGEXP.match(line) |
| 175 |
if m: |
| 176 |
oldnick = m.group(1) |
| 177 |
newnick = m.group(2) |
| 178 |
yield time, self.NICKCHANGE, (line, oldnick, newnick) |
| 179 |
elif self.SERVMSG_REGEXP.match(line): |
| 180 |
yield time, self.SERVER, line |
| 181 |
else: |
| 182 |
yield time, self.OTHER, line |
| 183 |
|
| 184 |
|
| 185 |
def open_log_file(filename): |
| 186 |
"""Open a log file for parsing.""" |
| 187 |
# We're dealing with text here. Why open the file in binary mode? |
| 188 |
# Simple: the Latin/Unicode hybrid encoding monstrosity described |
| 189 |
# at http://xchat.org/encoding/#hybrid. Python doesn't support this |
| 190 |
# natively, so we have to do the decoding ourselves. |
| 191 |
if filename.endswith('.gz'): |
| 192 |
return gzip.open(filename, 'rb') |
| 193 |
else: |
| 194 |
return open(filename, 'rb') |
| 195 |
|
| 196 |
|
| 197 |
def shorttime(time): |
| 198 |
"""Strip date and seconds from time. |
| 199 |
|
| 200 |
>>> print(shorttime('12:45:17')) |
| 201 |
12:45 |
| 202 |
>>> print(shorttime('12:45')) |
| 203 |
12:45 |
| 204 |
>>> print(shorttime('2005-02-04T12:45')) |
| 205 |
12:45 |
| 206 |
|
| 207 |
""" |
| 208 |
if 'T' in time: |
| 209 |
time = time.split('T')[-1] |
| 210 |
if time.count(':') > 1: |
| 211 |
time = ':'.join(time.split(':')[:2]) |
| 212 |
return time |
| 213 |
|
| 214 |
|
| 215 |
# |
| 216 |
# Colouring stuff |
| 217 |
# |
| 218 |
|
| 219 |
class ColourChooser: |
| 220 |
"""Choose distinguishable colours.""" |
| 221 |
|
| 222 |
def __init__(self, rgbmin=240, rgbmax=125, a=0.95, b=0.5): |
| 223 |
"""Define a range of colours available for choosing. |
| 224 |
|
| 225 |
`rgbmin` and `rgbmax` define the outmost range of colour depth (note |
| 226 |
that it is allowed to have rgbmin > rgbmax). |
| 227 |
|
| 228 |
`rgb`, if specified, is a list of (r,g,b) values where each component |
| 229 |
is between 0 and 1.0. |
| 230 |
|
| 231 |
If `rgb` is not specified, then it is constructed as |
| 232 |
[(a,b,b), (b,a,b), (b,b,a), (a,a,b), (a,b,a), (b,a,a)] |
| 233 |
|
| 234 |
You can tune `a` and `b` for the starting and ending concentrations of |
| 235 |
RGB. |
| 236 |
""" |
| 237 |
assert 0 <= rgbmin < 256 |
| 238 |
assert 0 <= rgbmax < 256 |
| 239 |
self.rgbmin = rgbmin |
| 240 |
self.rgbmax = rgbmax |
| 241 |
assert 0 <= a <= 1.0 |
| 242 |
assert 0 <= b <= 1.0 |
| 243 |
self.rgb = [ |
| 244 |
(a, b, b), |
| 245 |
(b, a, b), |
| 246 |
(b, b, a), |
| 247 |
(a, a, b), |
| 248 |
(a, b, a), |
| 249 |
(b, a, a), |
| 250 |
] |
| 251 |
|
| 252 |
def choose(self, i, n): |
| 253 |
"""Choose a colour. |
| 254 |
|
| 255 |
`n` specifies how many different colours you want in total. |
| 256 |
`i` identifies a particular colour in a set of `n` distinguishable |
| 257 |
colours. |
| 258 |
|
| 259 |
Returns a string '#rrggbb'. |
| 260 |
""" |
| 261 |
if n == 0: |
| 262 |
n = 1 |
| 263 |
r, g, b = self.rgb[i % len(self.rgb)] |
| 264 |
m = self.rgbmin + (self.rgbmax - self.rgbmin) * float(n - i) / n |
| 265 |
r, g, b = [int(c * m) for c in [r, g, b]] |
| 266 |
assert 0 <= r < 256 |
| 267 |
assert 0 <= g < 256 |
| 268 |
assert 0 <= b < 256 |
| 269 |
return '#%02x%02x%02x' % (r, g, b) |
| 270 |
|
| 271 |
|
| 272 |
class NickColourizer: |
| 273 |
"""Choose distinguishable colours for nicknames.""" |
| 274 |
|
| 275 |
def __init__(self, maxnicks=30, colour_chooser=None): |
| 276 |
"""Create a colour chooser for nicknames. |
| 277 |
|
| 278 |
If you know how many different nicks there might be, specify that |
| 279 |
numer as `maxnicks`. If you don't know, don't worry. |
| 280 |
|
| 281 |
If you really want to, you can specify a colour chooser. Default is |
| 282 |
ColourChooser(). |
| 283 |
""" |
| 284 |
if colour_chooser is None: |
| 285 |
colour_chooser = ColourChooser() |
| 286 |
self.colour_chooser = colour_chooser |
| 287 |
self.nickcount = 0 |
| 288 |
self.maxnicks = maxnicks |
| 289 |
self.nick_colour = {} |
| 290 |
|
| 291 |
def __getitem__(self, nick): |
| 292 |
colour = self.nick_colour.get(nick) |
| 293 |
if not colour: |
| 294 |
self.nickcount += 1 |
| 295 |
if self.nickcount >= self.maxnicks: |
| 296 |
self.maxnicks *= 2 |
| 297 |
colour = self.colour_chooser.choose(self.nickcount, self.maxnicks) |
| 298 |
self.nick_colour[nick] = colour |
| 299 |
return colour |
| 300 |
|
| 301 |
def change(self, oldnick, newnick): |
| 302 |
if oldnick in self.nick_colour: |
| 303 |
self.nick_colour[newnick] = self.nick_colour.pop(oldnick) |
| 304 |
|
| 305 |
|
| 306 |
# |
| 307 |
# HTML |
| 308 |
# |
| 309 |
|
| 310 |
URL_REGEXP = re.compile(r'((http|https|ftp|gopher|news)://([.,]*([^ \'")>&.,]|&))*)') |
| 311 |
|
| 312 |
|
| 313 |
def createlinks(text): |
| 314 |
"""Replace possible URLs with links. |
| 315 |
|
| 316 |
>>> print(createlinks('check out <http://example.com/a?b=c&c=d#e>!')) |
| 317 |
check out <<a href="http://example.com/a?b=c&c=d#e" rel="nofollow">http://example.com/a?b=c&c=d#e</a>>! |
| 318 |
|
| 319 |
>>> print(createlinks('http://example.com/a,')) |
| 320 |
<a href="http://example.com/a" rel="nofollow">http://example.com/a</a>, |
| 321 |
|
| 322 |
>>> print(createlinks('http://example.com/a.')) |
| 323 |
<a href="http://example.com/a" rel="nofollow">http://example.com/a</a>. |
| 324 |
|
| 325 |
>>> print(createlinks('http://example.com/a.b')) |
| 326 |
<a href="http://example.com/a.b" rel="nofollow">http://example.com/a.b</a> |
| 327 |
|
| 328 |
""" |
| 329 |
return URL_REGEXP.sub(r'<a href="\1" rel="nofollow">\1</a>', text) |
| 330 |
|
| 331 |
|
| 332 |
def escape(s): |
| 333 |
"""Replace ampersands, pointies, control characters. |
| 334 |
|
| 335 |
>>> print(escape('"Hello" & <world>')) |
| 336 |
"Hello" & <world> |
| 337 |
|
| 338 |
Control characters (ASCII 0 to 31) are stripped away |
| 339 |
|
| 340 |
>>> print(escape('[%s]' % ''.join([chr(x) for x in range(32)]))) |
| 341 |
[] |
| 342 |
|
| 343 |
""" |
| 344 |
s = s.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"') |
| 345 |
return ''.join([c for c in s if ord(c) > 0x1F]) |
| 346 |
|
| 347 |
|
| 348 |
# |
| 349 |
# Output styles |
| 350 |
# |
| 351 |
|
| 352 |
class AbstractStyle(object): |
| 353 |
"""A style defines the way output is formatted. |
| 354 |
|
| 355 |
This is not a real class, rather it is an description of how style |
| 356 |
classes should be written. |
| 357 |
""" |
| 358 |
|
| 359 |
name = "stylename" |
| 360 |
description = "Single-line description" |
| 361 |
charset = 'US-ASCII' |
| 362 |
|
| 363 |
def __init__(self, outfile, *, outfilename='', colours=None): |
| 364 |
"""Create a text formatter for writing to outfile. |
| 365 |
|
| 366 |
The ``colours`` dictionary may have the following items: |
| 367 |
|
| 368 |
- part |
| 369 |
- join |
| 370 |
- server |
| 371 |
- nickchange |
| 372 |
- action |
| 373 |
|
| 374 |
""" |
| 375 |
self.outfile = io.TextIOWrapper(outfile, encoding=self.charset, |
| 376 |
errors='xmlcharrefreplace', |
| 377 |
line_buffering=True) |
| 378 |
self.outfilename = os.path.basename(outfilename) |
| 379 |
self.colours = colours or {} |
| 380 |
self._anchors = set() |
| 381 |
|
| 382 |
def __del__(self): |
| 383 |
"""Destructor to make sure we don't close outfile prematurely.""" |
| 384 |
if not self.outfile.closed: |
| 385 |
self.outfile.flush() |
| 386 |
self.outfile.detach() # don't let TextIOWrapper.__del__ close it! |
| 387 |
|
| 388 |
def head(self, title, prev=('', ''), index=('', ''), next=('', ''), |
| 389 |
searchbox=False): |
| 390 |
"""Generate the header. |
| 391 |
|
| 392 |
`prev`, `index` and `next` are tuples (title, url) that comprise |
| 393 |
the navigation bar. |
| 394 |
""" |
| 395 |
|
| 396 |
def foot(self): |
| 397 |
"""Generate the footer.""" |
| 398 |
|
| 399 |
def servermsg(self, time, what, line): |
| 400 |
"""Output a generic server message. |
| 401 |
|
| 402 |
`time` is a string. |
| 403 |
`line` is not escaped. |
| 404 |
`what` is one of LogParser event constants (e.g. LogParser.JOIN). |
| 405 |
""" |
| 406 |
|
| 407 |
def nicktext(self, time, nick, text, htmlcolour): |
| 408 |
"""Output a comment uttered by someone. |
| 409 |
|
| 410 |
`time` is a string. |
| 411 |
`nick` and `text` are not escaped. |
| 412 |
`htmlcolour` is a string ('#rrggbb'). |
| 413 |
""" |
| 414 |
|
| 415 |
def timestamp_anchor(self, time): |
| 416 |
anchor = 't%s' % time |
| 417 |
if anchor in self._anchors: |
| 418 |
org_anchor = anchor |
| 419 |
for n in itertools.count(2): |
| 420 |
anchor = '%s-%d' % (org_anchor, n) |
| 421 |
if anchor not in self._anchors: |
| 422 |
break |
| 423 |
self._anchors.add(anchor) |
| 424 |
return anchor |
| 425 |
|
| 426 |
|
| 427 |
class SimpleTextStyle(AbstractStyle): |
| 428 |
"""Text style with little use of colour""" |
| 429 |
|
| 430 |
name = "simplett" |
| 431 |
description = __doc__ |
| 432 |
charset = 'iso-8859-1' |
| 433 |
|
| 434 |
def head(self, title, prev=None, index=None, next=None, searchbox=False): |
| 435 |
print("""\ |
| 436 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> |
| 437 |
<html> |
| 438 |
<head> |
| 439 |
\t<title>%(title)s</title> |
| 440 |
\t<meta name="generator" content="irclog2html.py %(VERSION)s by Marius Gedminas"> |
| 441 |
\t<meta name="version" content="%(VERSION)s - %(RELEASE)s"> |
| 442 |
\t<meta http-equiv="Content-Type" content="text/html; charset=%(charset)s"> |
| 443 |
\t<meta name="viewport" content="width=device-width, initial-scale=1"> |
| 444 |
</head> |
| 445 |
<body text="#000000" bgcolor="#ffffff"><tt>""" % { |
| 446 |
'VERSION': VERSION, |
| 447 |
'RELEASE': RELEASE, |
| 448 |
'title': escape(title), |
| 449 |
'charset': self.charset, |
| 450 |
}, file=self.outfile) |
| 451 |
|
| 452 |
def foot(self): |
| 453 |
print(""" |
| 454 |
<br>Generated by irclog2html.py %(VERSION)s by <a href="mailto:[email protected]">Marius Gedminas</a> |
| 455 |
- find it at <a href="%(HOMEPAGE)s">%(HOMEPAGE)s</a>! |
| 456 |
</tt></body></html>""" % {'VERSION': VERSION, |
| 457 |
'HOMEPAGE': escape(HOMEPAGE)}, |
| 458 |
end=' ', file=self.outfile) |
| 459 |
|
| 460 |
def servermsg(self, time, what, text): |
| 461 |
text = escape(text) |
| 462 |
text = createlinks(text) |
| 463 |
colour = self.colours.get(what) |
| 464 |
if colour: |
| 465 |
text = '<font color="%s">%s</font>' % (colour, text) |
| 466 |
self._servermsg(text) |
| 467 |
|
| 468 |
def _servermsg(self, line): |
| 469 |
print('%s<br>' % line, file=self.outfile) |
| 470 |
|
| 471 |
def nicktext(self, time, nick, text, htmlcolour): |
| 472 |
nick = escape(nick) |
| 473 |
text = escape(text) |
| 474 |
text = createlinks(text) |
| 475 |
text = text.replace(' ', ' ') |
| 476 |
self._nicktext(time, nick, text, htmlcolour) |
| 477 |
|
| 478 |
def _nicktext(self, time, nick, text, htmlcolour): |
| 479 |
print('<%s> %s<br>' % (nick, text), file=self.outfile) |
| 480 |
|
| 481 |
|
| 482 |
class TextStyle(SimpleTextStyle): |
| 483 |
"""Text style using colours for each nick""" |
| 484 |
|
| 485 |
name = "tt" |
| 486 |
description = __doc__ |
| 487 |
|
| 488 |
def _nicktext(self, time, nick, text, htmlcolour): |
| 489 |
print('<font color="%s"><%s></font>' |
| 490 |
' <font color="#000000">%s</font><br>' |
| 491 |
% (htmlcolour, nick, text), file=self.outfile) |
| 492 |
|
| 493 |
|
| 494 |
class SimpleTableStyle(SimpleTextStyle): |
| 495 |
"""Table style, without heavy use of colour""" |
| 496 |
|
| 497 |
name = "simpletable" |
| 498 |
|
| 499 |
def head(self, title, prev=None, index=None, next=None, searchbox=False): |
| 500 |
SimpleTextStyle.head(self, title, prev, index, next, searchbox) |
| 501 |
print("<table cellspacing=3 cellpadding=2 border=0>", file=self.outfile) |
| 502 |
|
| 503 |
def foot(self): |
| 504 |
print("</table>", file=self.outfile) |
| 505 |
SimpleTextStyle.foot(self) |
| 506 |
|
| 507 |
def _servermsg(self, line): |
| 508 |
print('<tr><td colspan=2><tt>%s</tt></td></tr>' % line, |
| 509 |
file=self.outfile) |
| 510 |
|
| 511 |
def _nicktext(self, time, nick, text, htmlcolour): |
| 512 |
print('<tr bgcolor="#eeeeee"><th><font color="%s">' |
| 513 |
'<tt>%s</tt></font></th>' |
| 514 |
'<td width="100%%"><tt>%s</tt></td></tr>' |
| 515 |
% (htmlcolour, nick, text), file=self.outfile) |
| 516 |
|
| 517 |
|
| 518 |
class TableStyle(SimpleTableStyle): |
| 519 |
"""Default style, using a table with bold colours""" |
| 520 |
|
| 521 |
name = "table" |
| 522 |
description = __doc__ |
| 523 |
|
| 524 |
def _nicktext(self, time, nick, text, htmlcolour): |
| 525 |
print('<tr><th bgcolor="%s"><font color="#ffffff">' |
| 526 |
'<tt>%s</tt></font></th>' |
| 527 |
'<td width="100%%" bgcolor="#eeeeee"><tt><font color="%s">%s</font></tt></td></tr>' |
| 528 |
% (htmlcolour, nick, htmlcolour, text), file=self.outfile) |
| 529 |
|
| 530 |
|
| 531 |
class XHTMLStyle(AbstractStyle): |
| 532 |
"""Text style, produces XHTML that can be styled with CSS""" |
| 533 |
|
| 534 |
name = 'xhtml' |
| 535 |
description = __doc__ |
| 536 |
charset = 'UTF-8' |
| 537 |
|
| 538 |
CLASSMAP = { |
| 539 |
LogParser.ACTION: 'action', |
| 540 |
LogParser.JOIN: 'join', |
| 541 |
LogParser.PART: 'part', |
| 542 |
LogParser.NICKCHANGE: 'nickchange', |
| 543 |
LogParser.SERVER: 'servermsg', |
| 544 |
LogParser.OTHER: 'other', |
| 545 |
} |
| 546 |
|
| 547 |
prefix = '<div class="irclog">' |
| 548 |
suffix = '</div>' |
| 549 |
|
| 550 |
def head(self, title, prev=('', ''), index=('', ''), next=('', ''), |
| 551 |
searchbox=False): |
| 552 |
self.prev = prev |
| 553 |
self.index = index |
| 554 |
self.next = next |
| 555 |
print("""\ |
| 556 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" |
| 557 |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
| 558 |
<html> |
| 559 |
<head> |
| 560 |
<meta http-equiv="Content-Type" content="text/html; charset=%(charset)s" /> |
| 561 |
<meta name="viewport" content="width=device-width, initial-scale=1" /> |
| 562 |
<title>%(title)s</title> |
| 563 |
<link rel="stylesheet" href="irclog.css" /> |
| 564 |
<meta name="generator" content="irclog2html.py %(VERSION)s by Marius Gedminas" /> |
| 565 |
<meta name="version" content="%(VERSION)s - %(RELEASE)s" /> |
| 566 |
</head> |
| 567 |
<body>""" % {'VERSION': VERSION, 'RELEASE': RELEASE, |
| 568 |
'title': escape(title), 'charset': self.charset}, file=self.outfile) |
| 569 |
self.heading(title) |
| 570 |
if searchbox: |
| 571 |
self.searchbox() |
| 572 |
self.navbar(prev, index, next) |
| 573 |
print(self.prefix, file=self.outfile) |
| 574 |
|
| 575 |
def heading(self, title): |
| 576 |
print('<h1>%s</h1>' % escape(title), file=self.outfile) |
| 577 |
|
| 578 |
def link(self, url, title): |
| 579 |
# Intentionally not escaping title so that &entities; work |
| 580 |
if url: |
| 581 |
print('<a href="%s">%s</a>' |
| 582 |
% (escape(quote(url)), title or escape(url)), |
| 583 |
end=' ', file=self.outfile) |
| 584 |
elif title: |
| 585 |
print('<span class="disabled">%s</span>' % title, |
| 586 |
end=' ', file=self.outfile) |
| 587 |
|
| 588 |
def searchbox(self): |
| 589 |
print(""" |
| 590 |
<div class="searchbox"> |
| 591 |
<form action="search" method="get"> |
| 592 |
<input type="text" name="q" id="searchtext" /> |
| 593 |
<input type="submit" value="Search" id="searchbutton" /> |
| 594 |
</form> |
| 595 |
</div> |
| 596 |
""", file=self.outfile) |
| 597 |
|
| 598 |
def navbar(self, prev, index, next): |
| 599 |
prev_title, prev_url = prev |
| 600 |
index_title, index_url = index |
| 601 |
next_title, next_url = next |
| 602 |
if not (prev_title or index_title or next_title or |
| 603 |
prev_url or index_url or next_url): |
| 604 |
return |
| 605 |
print('<div class="navigation">', end=' ', file=self.outfile) |
| 606 |
self.link(prev_url, prev_title) |
| 607 |
self.link(index_url, index_title) |
| 608 |
self.link(next_url, next_title) |
| 609 |
print('</div>', file=self.outfile) |
| 610 |
|
| 611 |
def foot(self): |
| 612 |
print(self.suffix, file=self.outfile) |
| 613 |
self.navbar(self.prev, self.index, self.next) |
| 614 |
print(""" |
| 615 |
<div class="generatedby"> |
| 616 |
<p>Generated by irclog2html.py %(VERSION)s by <a href="mailto:[email protected]">Marius Gedminas</a> |
| 617 |
- find it at <a href="%(HOMEPAGE)s">%(HOMEPAGE)s</a>!</p> |
| 618 |
</div> |
| 619 |
</body> |
| 620 |
</html>""" % {'VERSION': VERSION, |
| 621 |
'HOMEPAGE': escape(HOMEPAGE)}, file=self.outfile) |
| 622 |
|
| 623 |
def servermsg(self, time, what, text): |
| 624 |
"""Output a generic server message. |
| 625 |
|
| 626 |
`time` is a string. |
| 627 |
`line` is not escaped. |
| 628 |
`what` is one of LogParser event constants (e.g. LogParser.JOIN). |
| 629 |
""" |
| 630 |
text = escape(text) |
| 631 |
text = createlinks(text) |
| 632 |
if time: |
| 633 |
print( |
| 634 |
'<p id="{anchor}" class="{css_class}">' |
| 635 |
'<a href="{outfilename}#{anchor}" class="time">{time}</a>' |
| 636 |
' {text}</p>'.format( |
| 637 |
outfilename=self.outfilename, |
| 638 |
anchor=self.timestamp_anchor(time), |
| 639 |
css_class=self.CLASSMAP[what], |
| 640 |
time=shorttime(time), |
| 641 |
text=text), |
| 642 |
file=self.outfile) |
| 643 |
else: |
| 644 |
print( |
| 645 |
'<p class="{css_class}">{text}</p>'.format( |
| 646 |
css_class=self.CLASSMAP[what], text=text), |
| 647 |
file=self.outfile) |
| 648 |
|
| 649 |
def nicktext(self, time, nick, text, htmlcolour): |
| 650 |
"""Output a comment uttered by someone. |
| 651 |
|
| 652 |
`time` is a string. |
| 653 |
`nick` and `text` are not escaped. |
| 654 |
`htmlcolour` is a string ('#rrggbb'). |
| 655 |
""" |
| 656 |
nick = escape(nick) |
| 657 |
text = escape(text) |
| 658 |
text = createlinks(text) |
| 659 |
text = text.replace(' ', ' ') |
| 660 |
if time: |
| 661 |
print( |
| 662 |
'<p id="{anchor}" class="comment">' |
| 663 |
'<a href="{outfilename}#{anchor}" class="time">{time}</a> ' |
| 664 |
'<span class="nick" style="color: {color}">' |
| 665 |
'<{nick}></span>' |
| 666 |
' <span class="text">{text}</span></p>'.format( |
| 667 |
anchor=self.timestamp_anchor(time), |
| 668 |
outfilename=self.outfilename, |
| 669 |
time=shorttime(time), |
| 670 |
color=htmlcolour, |
| 671 |
nick=nick, |
| 672 |
text=text), |
| 673 |
file=self.outfile) |
| 674 |
else: |
| 675 |
print( |
| 676 |
'<p class="comment">' |
| 677 |
'<span class="nick" style="color: {color}">' |
| 678 |
'<{nick}></span>' |
| 679 |
' <span class="text">{text}</span></p>'.format( |
| 680 |
color=htmlcolour, |
| 681 |
nick=nick, |
| 682 |
text=text), |
| 683 |
file=self.outfile) |
| 684 |
|
| 685 |
|
| 686 |
class XHTMLTableStyle(XHTMLStyle): |
| 687 |
"""Table style, produces XHTML that can be styled with CSS""" |
| 688 |
|
| 689 |
name = 'xhtmltable' |
| 690 |
description = __doc__ |
| 691 |
|
| 692 |
prefix = '<table class="irclog">' |
| 693 |
suffix = '</table>' |
| 694 |
|
| 695 |
def servermsg(self, time, what, text, link=''): |
| 696 |
text = escape(text) |
| 697 |
text = createlinks(text) |
| 698 |
if time: |
| 699 |
print( |
| 700 |
'<tr id="{anchor}">' |
| 701 |
'<td class="{css_class}" colspan="2">{text}</td>' |
| 702 |
'<td><a href="{link}#{anchor}" class="time">{time}</a></td>' |
| 703 |
'</tr>'.format( |
| 704 |
anchor=self.timestamp_anchor(time), |
| 705 |
css_class=self.CLASSMAP[what], |
| 706 |
text=text, |
| 707 |
link=link or self.outfilename, |
| 708 |
time=shorttime(time)), |
| 709 |
file=self.outfile) |
| 710 |
else: |
| 711 |
print( |
| 712 |
'<tr>' |
| 713 |
'<td class="{css_class}" colspan="3">{text}</td>' |
| 714 |
'</tr>'.format( |
| 715 |
css_class=self.CLASSMAP[what], |
| 716 |
text=text), |
| 717 |
file=self.outfile) |
| 718 |
|
| 719 |
def nicktext(self, time, nick, text, htmlcolour, link=''): |
| 720 |
nick = escape(nick) |
| 721 |
text = escape(text) |
| 722 |
text = createlinks(text) |
| 723 |
text = text.replace(' ', ' ') |
| 724 |
link = link or self.outfilename |
| 725 |
if time: |
| 726 |
print( |
| 727 |
'<tr id="{anchor}">' |
| 728 |
'<th class="nick" style="background: {color}">{nick}</th>' |
| 729 |
'<td class="text" style="color: {color}">{text}</td>' |
| 730 |
'<td class="time">' |
| 731 |
'<a href="{link}#{anchor}" class="time">{time}</a></td>' |
| 732 |
'</tr>'.format( |
| 733 |
anchor=self.timestamp_anchor(time), |
| 734 |
color=htmlcolour, |
| 735 |
nick=nick, |
| 736 |
text=text, |
| 737 |
link=link, |
| 738 |
time=shorttime(time)), |
| 739 |
file=self.outfile) |
| 740 |
else: |
| 741 |
print( |
| 742 |
'<tr>' |
| 743 |
'<th class="nick" style="background: {color}">{nick}</th>' |
| 744 |
'<td class="text" colspan="2" style="color: {color}">{text}</td>' |
| 745 |
'</tr>'.format( |
| 746 |
color=htmlcolour, |
| 747 |
nick=nick, |
| 748 |
text=text), |
| 749 |
file=self.outfile) |
| 750 |
|
| 751 |
|
| 752 |
class MediaWikiStyle(AbstractStyle): |
| 753 |
"""Table style, produces MediaWiki syntax""" |
| 754 |
|
| 755 |
name = 'mediawiki' |
| 756 |
description = __doc__ |
| 757 |
|
| 758 |
def head(self, title, prev=('', ''), index=('', ''), next=('', ''), |
| 759 |
searchbox=False): |
| 760 |
print('{|', file=self.outfile) |
| 761 |
|
| 762 |
def servermsg(self, time, what, text, link=''): |
| 763 |
text = escape(text) |
| 764 |
# no need to call createlinks, MediaWiki parses links automatically |
| 765 |
if time: |
| 766 |
displaytime = shorttime(time) |
| 767 |
print('|- id="t%s"\n' |
| 768 |
'| colspan="2" | %s\n' |
| 769 |
'|| [[#t%s|%s]]' |
| 770 |
% (time, text, time, displaytime), file=self.outfile) |
| 771 |
else: |
| 772 |
print('|-\n' |
| 773 |
'| colspan="3" | %s' % text, file=self.outfile) |
| 774 |
|
| 775 |
def nicktext(self, time, nick, text, htmlcolour, link=''): |
| 776 |
nick = escape(nick) |
| 777 |
text = escape(text) |
| 778 |
# no need to call createlinks, MediaWiki parses links automatically |
| 779 |
if time: |
| 780 |
displaytime = shorttime(time) |
| 781 |
print('|- id="t%s"\n' |
| 782 |
'! style="background-color: %s" | %s\n' |
| 783 |
'| style="color: %s" | %s\n' |
| 784 |
'|| [[#t%s|%s]] ' |
| 785 |
% (time, htmlcolour, nick, htmlcolour, text, |
| 786 |
time, displaytime), file=self.outfile) |
| 787 |
else: |
| 788 |
print('|-\n' |
| 789 |
'| style="background-color: %s" | %s\n' |
| 790 |
'| style="color: %s" colspan="2" | %s ' |
| 791 |
% (htmlcolour, nick, htmlcolour, text), file=self.outfile) |
| 792 |
|
| 793 |
def foot(self): |
| 794 |
print('|}\n\nGenerated by irclog2html.py %(VERSION)s ' |
| 795 |
'by [mailto:[email protected] Marius Gedminas] - ' |
| 796 |
'find it at [%(HOMEPAGE)s %(HOMEPAGE)s]!' |
| 797 |
% {'VERSION': VERSION, 'HOMEPAGE': HOMEPAGE}, file=self.outfile) |
| 798 |
|
| 799 |
|
| 800 |
# |
| 801 |
# Main |
| 802 |
# |
| 803 |
|
| 804 |
# All styles |
| 805 |
STYLES = [ |
| 806 |
SimpleTextStyle, |
| 807 |
TextStyle, |
| 808 |
SimpleTableStyle, |
| 809 |
TableStyle, |
| 810 |
XHTMLStyle, |
| 811 |
XHTMLTableStyle, |
| 812 |
MediaWikiStyle, |
| 813 |
] |
| 814 |
|
| 815 |
# Customizable colours |
| 816 |
COLOURS = [ |
| 817 |
("part", "#000099", LogParser.PART), |
| 818 |
("join", "#009900", LogParser.JOIN), |
| 819 |
("server", "#009900", LogParser.SERVER), |
| 820 |
("nickchange", "#009900", LogParser.NICKCHANGE), |
| 821 |
("action", "#CC00CC", LogParser.ACTION), |
| 822 |
] |
| 823 |
|
| 824 |
|
| 825 |
def do_config_file(option, opt_str, value, parser): |
| 826 |
"""Read options from a config file and feed them back to optparse.""" |
| 827 |
options = [] |
| 828 |
try: |
| 829 |
with open(value) as f: |
| 830 |
for line in f: |
| 831 |
line = line.strip() |
| 832 |
if not line or line.startswith('#'): |
| 833 |
continue |
| 834 |
options.extend(shlex.split(line)) |
| 835 |
# Note: you can cause an infinite loop if you have a config file that |
| 836 |
# includes itself! Well, cause a RuntimeError actually. |
| 837 |
parser.rargs[:0] = options |
| 838 |
except IOError as e: |
| 839 |
raise optparse.OptionValueError("can't read config file: %s" % e) |
| 840 |
|
| 841 |
|
| 842 |
def parse_args(argv=sys.argv): |
| 843 |
parser = optparse.OptionParser("usage: %prog [options] filename [...]", |
| 844 |
version=VERSION, |
| 845 |
prog='irclog2html', |
| 846 |
description="Colourises and converts IRC" |
| 847 |
" logs to HTML format for easy" |
| 848 |
" web reading.") |
| 849 |
parser.add_option('-c', '--config', action='callback', type='str', |
| 850 |
metavar='FILE', callback=do_config_file, |
| 851 |
help="read options from a config file") |
| 852 |
parser.add_option('--dircproxy', action='store_true', default=False, |
| 853 |
help="dircproxy log file support (strips leading + or - from messages; off by default)") |
| 854 |
parser.add_option('-s', '--style', dest="style", default="xhtmltable", |
| 855 |
help="format log according to specific style" |
| 856 |
" (default: xhtmltable); try -s help for a list of" |
| 857 |
" available styles") |
| 858 |
parser.add_option('-t', '--title', dest="title", default=None, |
| 859 |
help="title of the page (default: same as file name)") |
| 860 |
parser.add_option('--prev-title', dest="prev_title", default='', |
| 861 |
help="title of the previous page (default: none)") |
| 862 |
parser.add_option('--prev-url', dest="prev_url", default='', |
| 863 |
help="URL of the previous page (default: none)") |
| 864 |
parser.add_option('--index-title', dest="index_title", default='', |
| 865 |
help="title of the index page (default: none)") |
| 866 |
parser.add_option('--index-url', dest="index_url", default='', |
| 867 |
help="URL of the index page (default: none)") |
| 868 |
parser.add_option('--next-title', dest="next_title", default='', |
| 869 |
help="title of the next page (default: none)") |
| 870 |
parser.add_option('--next-url', dest="next_url", default='', |
| 871 |
help="URL of the next page (default: none)") |
| 872 |
parser.add_option('-S', '--searchbox', action="store_true", dest="searchbox", |
| 873 |
default=False, |
| 874 |
help="include a search box") |
| 875 |
parser.add_option('-o', '--output-file', |
| 876 |
help="destination output file or directory" |
| 877 |
" (default: <input-file-name>.html)") |
| 878 |
for name, default, what in COLOURS: |
| 879 |
parser.add_option('--color-%s' % name, '--colour-%s' % name, |
| 880 |
dest="colour_%s" % name, default=default, |
| 881 |
help="select %s colour (default: %s)" |
| 882 |
% (name, default)) |
| 883 |
options, args = parser.parse_args(argv[1:]) |
| 884 |
return parser, options, args |
| 885 |
|
| 886 |
|
| 887 |
def pick_output_filename(input_filename): |
| 888 |
"""Pick a filename for the output file.""" |
| 889 |
if input_filename.endswith('.gz'): |
| 890 |
return input_filename[:-len('.gz')] + ".html" |
| 891 |
else: |
| 892 |
return input_filename + ".html" |
| 893 |
|
| 894 |
|
| 895 |
def main(argv=sys.argv): |
| 896 |
parser, options, args = parse_args(argv) |
| 897 |
if options.style == "help": |
| 898 |
print("The following styles are available for use with irclog2html.py:") |
| 899 |
for style in STYLES: |
| 900 |
print() |
| 901 |
print(" %s" % style.name) |
| 902 |
print(" %s" % style.description) |
| 903 |
print() |
| 904 |
return |
| 905 |
for style in STYLES: |
| 906 |
if style.name == options.style: |
| 907 |
break |
| 908 |
else: |
| 909 |
parser.error("unknown style: %s" % options.style) |
| 910 |
colours = {} |
| 911 |
for name, default, what in COLOURS: |
| 912 |
colours[what] = getattr(options, 'colour_%s' % name) |
| 913 |
if not args: |
| 914 |
parser.error("please specify a filename") |
| 915 |
title = options.title |
| 916 |
prev = (options.prev_title, options.prev_url) |
| 917 |
index = (options.index_title, options.index_url) |
| 918 |
next = (options.next_title, options.next_url) |
| 919 |
|
| 920 |
if len(args) > 1 and options.output_file and not os.path.isdir(options.output_file): |
| 921 |
parser.error("-o must be a directory when processing multiple files") |
| 922 |
for filename in args: |
| 923 |
try: |
| 924 |
infile = open_log_file(filename) |
| 925 |
except EnvironmentError as e: |
| 926 |
sys.exit("%s: cannot open %s for reading: %s" |
| 927 |
% (parser.prog, filename, e)) |
| 928 |
# Why open the output file in binary mode? We currently handle |
| 929 |
# encoding in our style classes, and they have different default |
| 930 |
# charsets, so it's simpler to just give a binary file to the |
| 931 |
# style class and let it deal with all the details. |
| 932 |
if not options.output_file: |
| 933 |
outfilename = pick_output_filename(filename) |
| 934 |
elif os.path.isdir(options.output_file): |
| 935 |
outfilename = os.path.join( |
| 936 |
options.output_file, |
| 937 |
os.path.basename(pick_output_filename(filename))) |
| 938 |
else: |
| 939 |
outfilename = options.output_file |
| 940 |
try: |
| 941 |
outfile = open(outfilename, "wb") |
| 942 |
except EnvironmentError as e: |
| 943 |
infile.close() |
| 944 |
sys.exit("%s: cannot open %s for writing: %s" |
| 945 |
% (parser.prog, outfilename, e)) |
| 946 |
try: |
| 947 |
parser = LogParser(infile, dircproxy=options.dircproxy) |
| 948 |
formatter = style(outfile, outfilename=outfilename, colours=colours) |
| 949 |
convert_irc_log(parser, formatter, title or filename, |
| 950 |
prev, index, next, searchbox=options.searchbox) |
| 951 |
css_file = os.path.join(os.path.dirname(outfilename), 'irclog.css') |
| 952 |
if not os.path.exists(css_file) and os.path.exists(CSS_FILE): |
| 953 |
shutil.copy(CSS_FILE, css_file) |
| 954 |
finally: |
| 955 |
outfile.close() |
| 956 |
infile.close() |
| 957 |
|
| 958 |
|
| 959 |
def convert_irc_log(parser, formatter, title, prev, index, next, |
| 960 |
searchbox=False): |
| 961 |
"""Convert IRC log to HTML or some other format.""" |
| 962 |
nick_colour = NickColourizer() |
| 963 |
formatter.head(title, prev, index, next, searchbox=searchbox) |
| 964 |
for time, what, info in parser: |
| 965 |
if what == LogParser.COMMENT: |
| 966 |
nick, text = info |
| 967 |
htmlcolour = nick_colour[nick] |
| 968 |
formatter.nicktext(time, nick, text, htmlcolour) |
| 969 |
else: |
| 970 |
if what == LogParser.NICKCHANGE: |
| 971 |
text, oldnick, newnick = info |
| 972 |
nick_colour.change(oldnick, newnick) |
| 973 |
else: |
| 974 |
text = info |
| 975 |
formatter.servermsg(time, what, text) |
| 976 |
formatter.foot() |
| 977 |
|
| 978 |
|
| 979 |
if __name__ == '__main__': |
| 980 |
main() |