forked from esitarski/CrossMgr
/
WebServer.py
629 lines (538 loc) · 17.5 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import os
import io
import re
import sys
import gzip
import glob
import time
import json
import threading
import datetime
import traceback
import urllib
import base64
from collections import defaultdict
from Queue import Queue
import socket
try:
# Python 2.x
from SocketServer import ThreadingMixIn
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
except ImportError:
# Python 3.x
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer
from qrcode import QRCode
from tornado.template import Template
from ParseHtmlPayload import ParseHtmlPayload
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse
from StringIO import StringIO
import Utils
import Model
from GetResults import GetResultsRAM, GetResultsBaseline, GetRaceName
from Synchronizer import syncfunc
from ThreadPoolMixIn import ThreadPoolMixIn
class CrossMgrServer(ThreadPoolMixIn, HTTPServer):
pass
reCrossMgrHtml = re.compile( r'^\d\d\d\d-\d\d-\d\d-.*\.html$' )
futureDate = datetime.datetime( datetime.datetime.now().year+20, 1, 1 )
with io.open( os.path.join(Utils.getImageFolder(), 'CrossMgr.ico'), 'rb' ) as f:
favicon = f.read()
def readBase64( fname ):
with io.open( os.path.join(Utils.getImageFolder(), fname), 'rb' ) as f:
return "data:image/png;base64," + base64.b64encode( f.read() )
with io.open( os.path.join(Utils.getImageFolder(), 'CrossMgrHeader.png'), 'rb' ) as f:
DefaultLogoSrc = readBase64('CrossMgrHeader.png')
icons = {
'QRCodeIconSrc': readBase64('QRCodeIcon.png'),
'CountdownIconSrc': readBase64('countdown.png'),
'StartListIconSrc': readBase64('tt_start_list.png'),
'LapCounterIconSrc': readBase64('lapcounter.png'),
'ResultsCurrentIconSrc': readBase64('results_current.png'),
'ResultsPreviousIconSrc': readBase64('results_previous.png'),
}
with io.open(os.path.join(Utils.getHtmlFolder(), 'Index.html'), encoding='utf-8') as f:
indexTemplate = Template( f.read() )
PORT_NUMBER = 8765
def gzipEncode( content ):
out = StringIO()
f = gzip.GzipFile(fileobj=out, mode='w', compresslevel=5)
f.write(content)
f.close()
return out.getvalue()
def validContent( content ):
return content.strip().endswith( '</html>' )
@syncfunc
def getCurrentHtml():
return Model.getCurrentHtml()
@syncfunc
def getCurrentTTCountdownHtml():
return Model.getCurrentTTCountdownHtml()
@syncfunc
def getCurrentTTStartListHtml():
return Model.getCurrentTTStartListHtml()
with io.open(os.path.join(Utils.getHtmlFolder(), 'LapCounter.html'), encoding='utf-8') as f:
lapCounterTemplate = f.read()
def getLapCounterHtml():
return lapCounterTemplate
def coreName( fname ):
return os.path.splitext(os.path.basename(fname).split('?')[0])[0].replace('_TTCountdown','').replace('_TTStartList','').strip('-')
class Generic( object ):
def __init__( self, **kwargs ):
self.__dict__.update( kwargs )
class ContentBuffer( object ):
Unchanged = 0
Changed = 1
ReadError = 2
ContentError = 3
def __init__( self ):
self.fileCache = {}
self.fnameRace = None
self.dirRace = None
self.lock = threading.Lock()
def _updateFile( self, fname, forceUpdate=False ):
if not self.fnameRace:
return None
if '_TTCountdown' in fname: # Force update the countdown so we get a valid timestamp.
forceUpdate = True
fnameBase = os.path.basename(fname).split('?')[0]
race = Model.race
if 'CoursePreview.html' in fnameBase or not reCrossMgrHtml.match(fnameBase):
return None
cache = self.fileCache.get( fname, {} )
fnameFull = os.path.join( self.dirRace, fname )
if race and self.fnameRace and coreName(self.fnameRace) == coreName(fnameFull):
if forceUpdate or race.lastChangedTime > cache.get('mtime',0.0):
if '_TTCountdown' in fname:
content = getCurrentTTCountdownHtml()
elif '_TTStartList' in fname:
content = getCurrentTTStartListHtml()
else:
content = getCurrentHtml()
if content:
cache['mtime'] = time.time()
result = ParseHtmlPayload( content=content )
cache['payload'] = result['payload'] if result['success'] else {}
cache['content'] = content.encode('utf-8')
cache['gzip_content'] = gzipEncode( cache['content'] )
cache['status'] = self.Changed
self.fileCache[fname] = cache
return cache
try:
mtime = os.path.getmtime( fnameFull )
except Exception as e:
self.fileCache.pop( fname, None )
return None
if not forceUpdate and (cache.get('mtime',None) == mtime and cache.get('content',None)):
cache['status'] = self.Unchanged
return cache
cache['status'] = self.Changed
try:
with io.open(fnameFull, encoding='utf-8') as f:
content = f.read()
except Exception as e:
cache['status'] = self.ReadError
return cache
if not validContent(content):
cache['status'] = self.ContentError
content = ''
cache['mtime'] = mtime
result = ParseHtmlPayload( content=content )
cache['payload'] = result['payload'] if result['success'] else {}
cache['content'] = content.encode('utf-8')
cache['gzip_content'] = gzipEncode( cache['content'] )
self.fileCache[fname] = cache
return cache
def reset( self ):
if self.fnameRace:
self.setFolder( self.fnameRace )
def setFNameRace( self, fnameRace ):
with self.lock:
self.fnameRace = fnameRace
self.dirRace = os.path.dirname( fnameRace )
coreNameRace = coreName( os.path.basename(fnameRace) )
self.fileCache = {}
self._updateFile( os.path.splitext(os.path.basename(fnameRace))[0] + '.html' )
for f in glob.glob( os.path.join(self.dirRace, '*.html') ):
self._updateFile( os.path.basename(f), coreName(os.path.basename(f)) == coreNameRace )
def _getFiles( self ):
return [fname for fname, cache in sorted(
self.fileCache.iteritems(),
key=lambda x: (x[1]['payload'].get('raceScheduledStart',futureDate), x[0])
) if not (fname.endswith('_TTCountdown.html') or fname.endswith('_TTStartList.html'))]
def _getCache( self, fname, checkForUpdate=True ):
if checkForUpdate:
cache = self._updateFile( fname )
else:
try:
cache = self.fileCache[fname]
except KeyError:
cache = self._updateFile( fname, True )
return cache
def getContent( self, fname, checkForUpdate=True ):
with self.lock:
cache = self._getCache( fname, checkForUpdate )
if cache:
return cache.get('content', ''), cache.get('gzip_content', None)
return '', None
def getIndexInfo( self ):
with self.lock:
race = Model.race
if not race:
return {}
result = {
'logoSrc': race.headerImage or DefaultLogoSrc,
'organizer': race.organizer.encode('utf-8'),
}
files = self._getFiles()
info = []
for fname in files:
cache = self._getCache( fname, False )
if not cache:
continue
payload = cache.get('payload', {})
fnameShow = os.path.splitext(os.path.basename(fname))[0].strip('-')
if fnameShow != 'Simulation':
fnameShow = fnameShow[11:]
g = Generic(
raceScheduledStart = payload.get('raceScheduledStart',None),
name = fnameShow,
categories = [
(
c['name'].encode('utf-8'),
urllib.quote(unicode(c['name']).encode('utf-8')),
c.get( 'starters', 0 ),
c.get( 'finishers', 0 ),
)
for c in payload.get('catDetails',[]) if c['name'] != 'All'],
url = urllib.pathname2url(fname),
isTimeTrial = payload.get('isTimeTrial',False),
raceIsRunning = payload.get('raceIsRunning',False),
raceIsFinished = payload.get('raceIsFinished',False),
)
if g.isTimeTrial:
g.urlTTCountdown = urllib.pathname2url(os.path.splitext(fname)[0] + '_TTCountdown.html')
g.urlTTStartList = urllib.pathname2url(os.path.splitext(fname)[0] + '_TTStartList.html')
else:
g.urlLapCounter = urllib.pathname2url('LapCounter.html')
info.append( g )
result['info'] = info
return result
#-----------------------------------------------------------------------
contentBuffer = ContentBuffer()
DEFAULT_HOST = None
def SetFileName( fname ):
if fname.endswith( '.cmn' ):
fname = os.path.splitext(fname)[0] + '.html'
q.put( {'cmd':'fileName', 'fileName':fname} )
def GetPreviousFileName():
file = None
try:
fnameCur = os.path.splitext(Model.race.getFileName())[0] + '.html'
except:
fnameCur = None
files = contentBuffer._getFiles()
try:
file = files[files.index(fnameCur)-1]
except:
pass
if file is None:
try:
file = files[-1]
except:
pass
return file
def getQRCodePage( urlPage ):
qr = QRCode()
qr.add_data( urlPage )
qr.make()
qrcode = '["' + '",\n"'.join(
[''.join( '1' if v else '0' for v in qr.modules[row] ) for row in xrange(qr.modules_count)]
) + '"]'
result = StringIO()
def w( s ):
result.write( s )
result.write( '\n' )
w( '<html>' )
w( '<head>' )
w( '''<style type="text/css">
body {
font-family: sans-serif;
text-align: center;
}
</style>''' )
w( '''<script>
function Draw() {
var qrcode={qrcode};
var c = document.getElementById("idqrcode");
var ctx = c.getContext("2d");
ctx.fillStyle = '#000';
var s = Math.floor( c.width / qrcode.length );
for( var y = 0; y < qrcode.length; ++y ) {
var row = qrcode[y];
for( var x = 0; x < row.length; ++x ) {
if( row.charAt(x) == '1' )
ctx.fillRect( x*s, y*s, s, s );
}
}
}
'''.replace('{qrcode}', qrcode) )
w( '</script>' )
w( '</head>' )
w( '<body onload="Draw();">' )
w( '<h1 style="margin-top: 32px;">Share Race Results</h1>' )
w( '<canvas id="idqrcode" width="360" height="360"></canvas>' )
w( '<h2>Scan the QRCode.<br/>Follow it to the Race Results page.</h2>' )
w( '<h2>{}</h2>'.format(urlPage) )
w( 'Powered by <a href="http://www.sites.google.com/site/crossmgrsoftware">CrossMgr</a>.' )
w( '</body>' )
w( '</html>' )
return result.getvalue().encode( 'utf-8' )
def getIndexPage( share=True ):
info = contentBuffer.getIndexInfo()
if not info:
return ''
info['share'] = share
info.update( icons )
return indexTemplate.generate( **info )
#---------------------------------------------------------------------------
def WriteHtmlIndexPage():
fname = os.path.join( os.path.dirname(Utils.getFileName()), 'index.html' )
try:
with io.open(fname, 'rb') as f:
previousContent = f.read()
except Exception as e:
previousContent = ''
content = getIndexPage(share=False)
if content != previousContent:
with io.open(fname, 'wb') as f:
f.write( getIndexPage(share=False) )
return fname
class CrossMgrHandler( BaseHTTPRequestHandler ):
html_content = 'text/html; charset=utf-8'
json_content = 'application/json'
reLapCounterHtml = re.compile( r'^\/LapCounter\d*\.html$' )
def do_GET(self):
up = urlparse.urlparse( self.path )
content, gzip_content = None, None
try:
if up.path=='/':
content = getIndexPage()
content_type = self.html_content
elif up.path=='/favicon.ico':
content = favicon
content_type = 'image/x-icon'
elif self.reLapCounterHtml.match( up.path ):
content = getLapCounterHtml()
content_type = self.html_content
elif up.path=='/qrcode.html':
urlPage = GetCrossMgrHomePage()
content = getQRCodePage( urlPage )
content_type = self.html_content
elif up.path=='/servertimestamp.html':
content = json.dumps( {
'servertime':time.time()*1000.0,
'requesttimestamp':float(up.query),
}
)
content_type = self.json_content;
else:
file = None
if up.path == '/CurrentResults.html':
try:
file = os.path.splitext(Model.race.getFileName())[0] + '.html'
except:
pass
elif up.path == '/PreviousResults.html':
file = GetPreviousFileName()
if file is None:
file = urllib.url2pathname(os.path.basename(up.path))
content, gzip_content = contentBuffer.getContent( file )
content_type = self.html_content
except Exception as e:
self.send_error(404,'File Not Found: {} {}\n{}'.format(self.path, e, traceback.format_exc()))
return
self.send_response( 200 )
self.send_header('Content-Type',content_type)
if content_type == self.html_content:
if gzip_content and 'Accept-Encoding' in self.headers and 'gzip' in self.headers['Accept-Encoding']:
content = gzip_content
self.send_header( 'Content-Encoding', 'gzip' )
self.send_header( 'Cache-Control', 'no-cache, no-store, must-revalidate' )
self.send_header( 'Pragma', 'no-cache' )
self.send_header( 'Expires', '0' )
self.send_header( 'Content-Length', len(content) )
self.end_headers()
self.wfile.write( content )
def log_message(self, format, *args):
return
#--------------------------------------------------------------------------
def GetCrossMgrHomePage( ip=None ):
if ip is None:
ip = not sys.platform.lower().startswith('win')
ip = True
if ip:
hostname = DEFAULT_HOST
else:
hostname = socket.gethostname()
try:
socket.gethostbyname( hostname )
except:
hostname = DEFAULT_HOST
return 'http://{}:{}'.format(hostname, PORT_NUMBER)
server = None
def WebServer():
global server
while 1:
try:
server = CrossMgrServer(('', PORT_NUMBER), CrossMgrHandler)
server.init_thread_pool()
server.serve_forever( poll_interval = 2 )
except Exception as e:
server = None
time.sleep( 5 )
def queueListener( q ):
global DEFAULT_HOST, server
DEFAULT_HOST = Utils.GetDefaultHost()
keepGoing = True
while keepGoing:
message = q.get()
cmd = message.get('cmd', None)
if cmd == 'fileName':
DEFAULT_HOST = Utils.GetDefaultHost()
contentBuffer.setFNameRace( message['fileName'] )
elif cmd == 'exit':
keepGoing = False
q.task_done()
if server:
server.shutdown()
server = None
q = Queue()
qThread = threading.Thread( target=queueListener, name='queueListener', args=(q,) )
qThread.daemon = True
qThread.start()
webThread = threading.Thread( target=WebServer, name='WebServer' )
webThread.daemon = True
webThread.start()
from websocket_server import WebsocketServer
#-------------------------------------------------------------------
def message_received(client, server, message):
msg = json.loads( message )
if msg['cmd'] == 'send_baseline' and (msg['raceName'] == 'CurrentResults' or msg['raceName'] == GetRaceName()):
server.send_message( client, json.dumps(GetResultsBaseline()) )
wsServer = None
def WsServerLaunch():
global wsServer
while 1:
try:
wsServer = WebsocketServer( port=PORT_NUMBER + 1, host='' )
wsServer.set_fn_message_received( message_received )
wsServer.run_forever()
except Exception as e:
wsServer = None
time.sleep( 5 )
def WsQueueListener( q ):
global wsServer
keepGoing = True
while keepGoing:
message = q.get()
if message.get('cmd', None) == 'exit':
keepGoing = False
elif wsServer and wsServer.hasClients():
wsServer.send_message_to_all( json.dumps(message) )
q.task_done()
wsServer = None
wsQ = Queue()
wsQThread = threading.Thread( target=WsQueueListener, name='WsQueueListener', args=(wsQ,) )
wsQThread.daemon = True
wsQThread.start()
wsThread = threading.Thread( target=WsServerLaunch, name='WsServer' )
wsThread.daemon = True
wsThread.start()
wsTimer = None
wsTimerDur = None
wsTimerDurMax = 4
def WsPost():
global wsTimer
if wsServer.hasClients():
ram = GetResultsRAM()
if ram:
wsQ.put( ram )
if wsTimer:
wsTimer.cancel()
wsTimer = None
def WsRefresh( updatePrevious=False ):
if updatePrevious:
wsQ.put( {'cmd':'reload_previous'} )
return
global wsTimer, wsTimerDur
if not wsTimer:
wsTimerDur = 1.0
wsTimer = threading.Timer( wsTimerDur, WsPost )
wsTimer.start()
else:
if wsTimerDur < wsTimerDurMax:
wsTimerDur *= 1.5
wsTimer.cancel()
wsTimer = threading.Timer( wsTimerDur, WsPost )
wsTimer.start()
#-------------------------------------------------------------------
def GetLapCounterRefresh():
try:
return Utils.mainWin.lapCounter.GetState()
except:
return { 'cmd':'refresh', 'labels':[], 'foregrounds':[], 'backgrounds':[] }
def lap_counter_new_client(client, server):
server.send_message( client, json.dumps(GetLapCounterRefresh()) )
wsLapCounterServer = None
def WsLapCounterServerLaunch():
global wsLapCounterServer
while 1:
try:
wsLapCounterServer = WebsocketServer( port=PORT_NUMBER + 2, host='' )
wsLapCounterServer.set_fn_new_client( lap_counter_new_client )
wsLapCounterServer.run_forever()
except Exception as e:
wsLapCounterServer = None
time.sleep( 5 )
def WsLapCounterQueueListener( q ):
global wsLapCounterServer
keepGoing = True
while keepGoing:
message = q.get()
cmd = message.get('cmd', None)
if cmd == 'refresh':
if wsLapCounterServer and wsLapCounterServer.hasClients():
wsLapCounterServer.send_message_to_all( json.dumps(message) )
elif cmd == 'exit':
keepGoing = False
q.task_done()
wsLapCounterServer = None
wsLapCounterQ = Queue()
wsLapCounterQThread = threading.Thread( target=WsLapCounterQueueListener, name='WsLapCounterQueueListener', args=(wsLapCounterQ,) )
wsLapCounterQThread.daemon = True
wsLapCounterQThread.start()
wsLapCounterThread = threading.Thread( target=WsLapCounterServerLaunch, name='WsLapCounterServer' )
wsLapCounterThread.daemon = True
wsLapCounterThread.start()
lastRaceName, lastMessage = None, None
def WsLapCounterRefresh():
global lastRaceName, lastMessage
race = Model.race
if not (race and race.isRunning()):
return
if not (wsLapCounterServer and wsLapCounterServer.hasClients()):
return
message, raceName = GetLapCounterRefresh(), GetRaceName()
if lastMessage != message or lastRaceName != raceName:
wsLapCounterQ.put( message )
lastMessage, lastRaceName = message, raceName
if __name__ == '__main__':
SetFileName( os.path.join('Gemma', '2015-11-10-A Men-r4-.html') )
print 'Started httpserver on port ' , PORT_NUMBER
try:
time.sleep( 10000 )
except KeyboardInterrupt:
q.put( {'cmd':'exit'} )