-
Notifications
You must be signed in to change notification settings - Fork 1
/
logformat.py
executable file
·266 lines (221 loc) · 9.37 KB
/
logformat.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
from sys import argv
import re
import time
import locale
import os
try:
from mod_python import apache
except:
pass
class chatlog:
def __init__(self, textlog, language, plain=False):
"""
Input a text/plain chatlog from zweipktfkt and get out HTML5 goodness.
"""
# precompile regular expressions
hosts_re = re.compile(r'(^[0-9]{2}:[0-9]{2} [^<][^ ]*) \(.*@.*\) (has (joined|quit|left))')
chars_re = re.compile(u'[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]')
uri_patterns = [ r'''((?<=\()\b[A-Za-z][A-Za-z0-9\+\.\-]*:([A-Za-z0-9\.\-_~:/\?#\[\]@!\$&'\(\)\*\+,;=]|%[A-Fa-f0-9]{2})+(?=\)))''', r'''((?<=<)\b[A-Za-z][A-Za-z0-9\+\.\-]*:([A-Za-z0-9\.\-_~:/\?#\[\]@!\$&'\(\)\*\+,;=]|%[A-Fa-f0-9]{2})+(?=>))''', r'''(?<!\()\b([A-Za-z][A-Za-z0-9\+\.\-]*:([A-Za-z0-9\.\-_~:/\?#\[\]@!\$&'\(\)\*\+,;=]|%[A-Fa-f0-9]{2})+)''', ]
uri_res = [re.compile(p) for p in uri_patterns]
twittername_re = re.compile(r"(?<=[^a-zA-Z0-9_])(@([a-zA-Z0-9_]{2,}))(?=[^a-zA-Z0-9_]|$)")
# remove illegal unicode <http://stackoverflow.com/questions/1707890/fast-way-to-filter-illegal-xml-unicode-chars-in-python#answer-22273639>
_illegal_unichrs = [(0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F),
(0x7F, 0x84), (0x86, 0x9F),
(0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)]
_illegal_ranges = ["%s-%s" % (unichr(low), unichr(high))
for (low, high) in _illegal_unichrs]
_illegal_xml_chars_re = re.compile(u'[%s]' % u''.join(_illegal_ranges))
self.log = ""
firstline = textlog.split("\n")[0]
try:
locale.setlocale(locale.LC_ALL, "en_US.utf-8")
datetime = time.strptime(firstline[15:])
except ValueError:
locale.setlocale(locale.LC_ALL, "de_DE.utf-8")
datetime = time.strptime(firstline[15:])
locale.setlocale(locale.LC_ALL, "de_DE.utf-8")
if not plain:
self.log += '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="''' + language + '''">
<head>
<title>Log für ''' + time.strftime("%A, den %d. %B %Y", datetime) + '''</title>
<link rel="stylesheet" href="css/tango.css" title="Defaul-Stil" type="text/css"/>
</head>
<body>
<a class="plaintextlink" href="?mode=plain">Plaintext</a><br />
<label for="compact">
<input type="checkbox" id="compact" onclick="save()"/> Compact
</label>
<script><![CDATA[
document.addEventListener("DOMContentLoaded", restore, false);
function restore() {
var checkbox = document.getElementById('compact');
var storage = localStorage;
if (storage.getItem('compacted') == 'true') {
checkbox.checked = 'true';
}
showhide();
}
function save() {
var checkbox = document.getElementById('compact');
var storage = localStorage;
storage.setItem('compacted', checkbox.checked)
showhide();
}
function showhide() {
var checkbox = document.getElementById('compact');
var head = document.getElementsByTagName("head")[0];
// not using localStorage here, so this also works in older browsers
if (checkbox.checked) {
// hide non-dialog lines
var style = document.createElement('style');
style.id = 'compact-css';
style.textContent = '.non-dialog, .non-dialog + br { display: none; }';
head.appendChild(style);
} else {
// show non-dialog lines
var style = document.getElementById('compact-css');
head.removeChild(style);
}
}
]]></script>
<!-- link to last line -->'''
lastlineid = 1
for lineid, line in enumerate(textlog.split("\n")):
# remove hosts
line = hosts_re.sub(r'\1 \2', line)
# replace xml chars
if not plain:
line = line.replace("&","&")
line = line.replace("<","<")
line = line.replace(">",">")
line = line.replace("'","'")
line = line.replace("\"",""")
# input is mixed utf-8 and latin-1
try:
line = unicode(line,'utf-8','strict')
# remove unicode illegal in XML
line, count = _illegal_xml_chars_re.subn('', line)
except UnicodeDecodeError:
line = unicode(line,'latin-1','strict')
if plain:
line = line.encode('utf-8')
else:
line = line.encode('ascii', 'xmlcharrefreplace')
line, count = chars_re.subn('',line)
# remove erroneous spaces
try:
if line[10] == " ":
line = line[:10] + line[11:]
except IndexError:
pass
if not plain:
# markup log time, add anchors, mark non-speak lines
try:
int(line[:2])
int(line[3:5])
line = '<span class="time">' + line[:5] + '</span>' + line[5:]
if line[32:36] == "<":
line = '<a class="line-marker" href="#' + str(lineid) + '">#</a><span class="line dialog" id="' + str(lineid) + '">' + line + '</span>'
else:
line = '<a class="line-marker non-dialog" href="#' + str(lineid) + '">#</a><span class="line non-dialog" id="' + str(lineid) + '">' + line + '</span>'
lastlineid = lineid
except ValueError:
pass
# markup links
uri_replacement = r'''<a href="\1">\1</a>'''
for p in uri_res:
line, nsubs = p.subn(uri_replacement, line)
if nsubs > 0: break # only use first matching pattern
# markup twitter names
line = twittername_re.sub(r'''<a href="https://twitter.com/\2" class="twitter-link">\1</a>''',line)
self.log += line + ("\n" if plain else "<br/>\n")
if (not plain) and line == textlog.split("\n")[-1:][0]:
link = '''<a class="line-link" id="1" href="#''' + str(lastlineid) + '''">⤓</a>'''
self.log = self.log.replace("<!-- link to last line -->", link)
if not plain:
self.log += """</body>
</html>"""
def __str__(self):
return self.log
class DirectoryListing:
def __init__(self, path, language):
self.listing = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="''' + language + '''">
<head>
<title>Logs</title>
<link rel="stylesheet" href="css/tango.css" title="Defaul-Stil" type="text/css"/>
</head>
<body>
'''
files = [l for l in os.listdir(path) if l[-4:] == ".log"]
files.sort()
files.reverse()
for f in files:
self.listing += "<a href=\"" + f + "\">" + f[:-4] + "</a>"
self.listing += " (<a href=\"" + f + "?mode=plain\">plain</a>)"
self.listing += "<br />\n"
self.listing += """</body>
</html>"""
def __str__(self):
return self.listing
if __name__ == '__main__':
infile = argv[1]
if os.path.isdir(infile):
outfile = os.path.join(infile, "index.xhtml")
g = open(outfile,"w")
g.write(str(DirectoryListing(infile, "de")))
g.close()
else:
outfile = infile + ".xhtml"
f = open(infile, "r")
input = f.read()
f.close()
nicelog = str(chatlog(input, "de"))
g = open(outfile, "w")
g.write(nicelog)
g.close()
def handler(req):
# generate an index
if req.filename[-12:] == "logformat.py":
req.content_type = "application/xhtml+xml; charset=UTF8"
req.write(str(DirectoryListing(os.path.dirname(req.filename), "de")))
return apache.OK
if req.args != None:
params = dict([part.split('=') for part in req.args.split('&')])
if 'mode' in params and params['mode'] == 'plain':
plain = True
else:
plain = False
else:
plain = False
try:
f = open(req.filename)
except IOError:
return apache.HTTP_NOT_FOUND
if plain:
req.content_type = "text/plain; charset=UTF8"
req.write(str(chatlog(f.read(),"de",plain=True)))
else:
req.content_type = "application/xhtml+xml; charset=UTF8"
req.write(str(chatlog(f.read(),"de",plain=False)))
f.close()
return apache.OK