-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.py
345 lines (306 loc) · 11.4 KB
/
webserver.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
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
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import os
import re
import threading
import logging
import json
import random
import time
import SimpleHTTPServer
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# create logger
log = logging.getLogger('web')
log.setLevel(logging.DEBUG)
# add ch to logger
log.addHandler(ch)
style = {'light':"""
a{
text-decoration: none;
color:#666;
}
a:hover{
color:#aaa;
}
body {
font-family:Calibri,Helvetica,Arial;
font-size:12pt;
color:#111;
}
hr {
color:#111;
background-color:#555;
}
table.tablesorter {
background-color: #CDCDCD;
font-family: Calibri,Helvetica,Arial;
font-size: 9pt;
margin: 10px 10px 15px 10px;
text-align:left;
}
table.tablesorter thead tr th tfoot {
background-color:#E6EEEE;
border:1px solid #FFFFFF;
font-size:9pt;
padding:4px 40px 4px 4px;
background-position:right center;
background-repeat:no-repeat;
cursor:pointer;
}
table.tablesorter tbody td {
background-color:#FFFFFF;
color:#3D3D3D;
padding:4px;
vertical-align:top;
}
table.tablesorter tbody tr.odd td {
background-color:#F0F0F6;
}
table.tablesorter thead tr .headerSortUp {
background-image:url("asc.gif");
}
table.tablesorter thead tr .headerSortDown {
background-image:url("desc.gif");
}
table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
background-color:#8DBDD8;
}
""",
'dark':"""
body,iframe,textarea,input,button,file,.but{
font-family: Arial, "MS Trebuchet", sans-serif;
background-color: #292929;
color:#aaa;
border-color:#404040;
}
a{
text-decoration: none;
color:#bbb;
}
a:hover{
color:#ddd;
}
table.tablesorter thead th tr tfoot {
text-align: left;
background-color:#666666;
border-color:#CCCCCC;
}
table.tablesorter tbody td tfoot {
text-align: left;
border: 1;
border-color:#CCCCCC;
}
"""
}
class AntsGameServer(HTTPServer):
def __init__(self, *args):
self.db = None
self.opts = None
HTTPServer.__init__(self, *args)
class AntsGameHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def __init__(self, *args):
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args)
def header(self, title):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
return """<html><head>
<link rel="icon" href='/favicon.ico'>
<title>""" + title + """</title>
<style>""" + style[self.server.opts['style']] + """</style>
</head><body>
<a href='/' name=top> Latest Games </a>
<a href='/ranking'> Rankings </a>
<a href='/tcpclient.py' title='get the python client'> Client.py </a>
<br><p>
"""
def footer(self):
anum = int(1 + random.random() * 12)
apic = "<img src='/ants_pics/a"+str(anum)+".png' border=0>"
return "<p><br> <a href=#top title='crawl back to the top'> " + apic + "</a>"
def serve_visualizer(self, match):
junk,gid = match.group(0).split('.')
rep_file = os.getcwd() + "/games/" + gid + ".replay"
f = open(rep_file)
replaydata = f.read()
f.close()
html = """
<html>
<head>
<title>Ant Canvas</title>
<script type="text/javascript" src="/js/visualizer.js"></script>
<script type="text/javascript">
window.isFullscreenSupported = function() {
return false;
};
function init() {
var visualizer = new Visualizer(document.body, '/data/');
visualizer.loadReplayData('"""+replaydata+"""');
}
</script>
<style type="text/css">
html { margin:0; padding:0; }
body { margin:0; padding:0; overflow:hidden; }
</style>
</head>
<body>
<script>init();</script>
</body>
</html>
"""
self.wfile.write(html)
def game_head(self):
return """<table id='myTable' class='tablesorter' width='100%'>
<thead><tr><th>Game </th><th>Players</th><th>Date</th><th>Map</th></tr></thead>"""
def game_line(self, g):
html = "<tr><td><a href='/replay." + str(g.id) + "' title='Run in Visualizer'> Replay " + str(g.id) + "</a></td><td>"
for key, value in sorted(g.players.iteritems(), key=lambda (k,v): (v,k), reverse=True):
html += " <a href='/player/" + str(key) + "'>"+str(key)+"</a> (" + str(value) + ") "
html += "</td><td>" + str(g.date) + "</td>"
html += "<td><a href='/map/" + str(g.map) + "' title='View the map'>" + str(g.map) + "</a></td>"
html += "</tr>"
return html
def rank_head(self):
return """<table id='plTable' class='tablesorter' width='100%'>
<thead><tr><th>Player</th><th>Skill</th><th>Mu</th><th>Sigma</th><th>Games</th></tr></thead>"""
def rank_line( self, p ):
html = "<tr><td><a href='/player/" + str(p.name) + "'>"+str(p.name)+"</a></td>"
html += "<td>" + str(p.skill) + "</td>"
html += "<td>" + str(p.mu) + "</td>"
html += "<td>" + str(p.sigma) + "</td>"
#~ html += "<td>" + str(len(p.games)) + "</td>"
html += "<td>" + str(p.ngames) + "</td>"
html += "</tr>"
return html
def serve_main(self):
html = self.header("latest games on " + str(self.server.opts['host']) )
html += self.game_head()
html += "<tbody>"
for k,g in sorted(self.server.db.games.iteritems(), reverse=True):
html += self.game_line(g)
html += "</tbody></table>"
html += self.footer()
html += "</body></html>"
self.wfile.write(html)
def serve_player(self, match):
player = match.group(0).split("/")[2]
log.info( "PLAYER : " + match.group(0) )
html = self.header( player )
html += self.rank_head()
html += "<tbody>"
html += self.rank_line( self.server.db.players[player] )
html += "</tbody></table>"
html += self.game_head()
html += "<tbody>"
for k,g in sorted(self.server.db.games.iteritems(), reverse=True):
if player in g.players:
html += self.game_line(g)
html += "</tbody></table>"
html += self.footer()
html += "</body></html>"
self.wfile.write(html)
def serve_ranking(self, match):
html = self.header("Rankings")
html += self.rank_head()
html += "<tbody>"
def by_skill( a,b ):
return cmp(b[1].skill, a[1].skill)
pz = self.server.db.players.items()
pz.sort(by_skill)
for n,p in pz:
html += self.rank_line( p )
html += "</tbody></table>"
html += self.footer()
html += "</body></html>"
self.wfile.write(html)
def serve_map( self, match ):
style = """
<style>
.A { border:0; background-color:#f0f; width:5; height:5; }
.B { border:0; background-color:#f00; width:5; height:5; }
.C { border:0; background-color:#0f0; width:5; height:5; }
.D { border:0; background-color:#0ff; width:5; height:5; }
.E { border:0; background-color:#ccc; width:5; height:5; }
.F { border:0; background-color:#ff0; width:5; height:5; }
.G { border:0; background-color:#22a; width:5; height:5; }
</style>
"""
mapname = match.group(0).split('/')[2]
fname = os.getcwd() + "/maps/symmetric_maps/" + mapname
f = open(fname,"rb")
m = f.read()
f.close()
if 0:
result = """<div id="map_div"><div id="map_center">
<div id="map_title">cavern map with rotational symmetry</div>
<canvas id="map" width="600" height="400" />
<!--[if lt IE 9]><script type="text/javascript">
var ready = false;
document.getElementById('map_center').removeChild(document.getElementById('map'));
InsertCanvasObject("map", 400, 400, "/static/", function() { ready = true; });
</script><![endif]-->
</div></div>"""
else:
result = self.header(mapname) + style + "<table border=0>\r\n"
for line in m.split('\n'):
line = line.strip().lower()
# ignore blank lines and comments
if not line or line[0] == '#':
continue
key, value = line.split(' ')
if key == 'm':
result +="<tr>"
for pix in value:
if pix=='a': c='A'
if pix=='b': c='B'
if pix=='c': c='C'
if pix=='d': c='D'
if pix=='.': c='E'
if pix=='*': c='F'
if pix=='%': c='G'
result +="<td class='"+c+"'/>"
result +="<tr>"
result += "</table>" + self.footer()
self.wfile.write(result)
def serve_file(self, match):
mime = {'png':'image/png','jpg':'image/jpeg','jpeg':'image/jpeg','gif':'image/gif','js':'text/javascript','py':'application/python'}
junk,end = match.group(0).split('.')
try:
mime_type = mime[end]
except:
mime_type = 'text/plain'
fname = os.getcwd() + match.group(0)
f = open(fname,"rb")
self.send_response(200)
self.send_header('Content-type',mime_type)
self.end_headers()
self.wfile.write(f.read())
f.close()
def do_GET(self):
log.info(self.path)
if self.path == '/':
self.serve_main()
return
for regex, func in (
('^\/ranking', self.serve_ranking),
('^\/map/(.*)', self.serve_map),
('^\/player\/(.*)', self.serve_player),
('^\/replay\.([0-9]+)', self.serve_visualizer),
('^\/?(.*)', self.serve_file),
):
match = re.search(regex, self.path)
if match:
func(match)
return
self.send_error(404, 'File Not Found: %s' % self.path)
#~ if __name__ == '__main__':
#~ PORT = 2080
#~ httpd = AntsGameServer(('', PORT), AntsGameHandler)
#~ log.info('serving at port %d' % PORT)
#~ httpd.serve_forever()