-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
240 lines (191 loc) · 5.92 KB
/
server.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
#!/usr/bin/env python2.7
import os
import random
import re
import signal
import sys
import time
import traceback
from bottle import route, run, template, static_file, abort, Bottle, request, redirect
from threading import Semaphore
import counter
clients = {}
current_message = ""
#####################################################################
#
# Signal Handlers
#
#####################################################################
def quit_handler(signum, frame):
""" save dice roller state """
pass
#####################################################################
#
# Bottle Routing
#
#####################################################################
# initialization bits
app = Bottle()
die_lock = Semaphore()
dice_stats = counter.Dice_Roll_Stats()
@app.route('/')
@app.route('/create')
def main():
# generate uniq id, then redirect to that page
uid = '%030x' % random.randrange(16**30)
while uid in clients.keys():
uid = '%030x' % random.randrange(16**30)
return redirect("/roller/%s" % uid)
@app.route('/static/<path:path>')
def static(path):
return static_file(path, root="./static")
@app.route('/roller/<uid>')
def roller(uid):
return template("dorolls")
@app.route('/viewer/<uid>')
def roller(uid):
return template("viewrolls")
@app.route('/test/roll/<msg>')
def testroll(msg):
return parse_roll(msg)
@app.route('/test/stats')
def stats():
return dice_stats.grab_stats(True)
@app.route('/ws/roller/<uid>')
@app.route('/ws/viewer/<uid>')
def ws(uid):
"""
websocket code
"""
print >>sys.stderr, "websocket called"
wsock = request.environ.get('wsgi.websocket')
if not wsock:
print >>sys.stderr, "no websock environ"
print >>sys.stderr, request.environ
abort(400, 'Expected WebSocket request.')
if not clients.has_key(uid):
clients[uid] = []
clients[uid].append(wsock)
while True:
try:
print >>sys.stderr, "waiting for msg"
message = wsock.receive()
print >>sys.stderr, "msg received"
if message != None:
handle_ws(uid, message, wsock)
else:
try:
clients[uid].remove(wsock)
except ValueError:
pass
if len(clients[uid]) == 0:
del(clients[uid])
except WebSocketError:
try:
clients[uid].remove(wsock)
if len(clients[uid]) == 0:
del(clients[uid])
except ValueError:
pass # already cleaned up
except KeyError:
pass # already cleaned up
break
print >>sys.stderr, "websock destroyed"
#####################################################################
#
# Bottle helpers
#
#####################################################################
def handle_ws(uid, message, ws):
"""
fall through opcodes do do work
"""
global current_message
if "," in message:
op, message = message.split(",", 1)
op = int(op)
elif message.strip().isdigit():
op = int(message)
message = ""
else:
print >> sys.stderr,"WTF is '%s'" % str(message)
if op == 0:
pass
elif op == 1:
retmsg = parse_roll(message)
retmsg = "1,%s" % str(retmsg)
send_to_all_ws(uid, retmsg)
def send_to_all_ws(uid, message):
for s in clients[uid][:]:
try:
s.send(message)
print "sent 1"
except WebSocketError:
traceback.print_exc()
clients.remove(s)
def parse_roll(msg):
dice = []
try:
if "," in msg:
for msg_part in msg.split(","):
dice.append(parse_dice_msg(msg_part))
else:
dice.append(parse_dice_msg(msg))
except Exception:
return None
return perform_and_format_roll(msg, dice)
def perform_and_format_roll(msg, dice):
results = []
total = 0
for rolls in dice:
die = int(rolls['die'])
midresult = []
if rolls['modifier']:
midresult.append("((")
dierolls = []
save_dice = (die == 20)
for i in xrange(int(rolls['quantity'])):
rolled = random.randint(1, die)
dierolls.append(rolled)
if save_dice:
try:
die_lock.acquire()
dice_stats.increment(rolled)
die_lock.release()
except:
print traceback.format_exc()
total += sum(dierolls)
dierolls = map(str, dierolls)
midresult.append(" + ".join(dierolls))
if rolls['modifier']:
midresult.append(")")
midresult.append(rolls['modifier'])
midresult.append(")")
total += int(rolls['modifier'])
results.append(" ".join(midresult))
return "%s: %s = %d" % (msg, " + ".join(results), total)
def parse_dice_msg(msg):
""" msg format here should be [0-9]+d[0-9]+([+-][0-9]+)? """
msg = msg.strip().lower()
result = re.match("(?P<quantity>[0-9]+)d(?P<die>[0-9]+)(?P<modifier>[+-][0-9]+)?", msg)
if result:
return result.groupdict()
else:
raise Exception("ugh, not valid dice roll")
if quantity.isdigit() and value.isdigit():
return [ int(value) ] * int(quantity)
else:
raise Exception("ugh, not valid dice roll")
#####################################################################
#
# Initialization Code
#
#####################################################################
#run(host='0.0.0.0', port=8080, server="paste")
#run(host='0.0.0.0', port=8080)
from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
server = WSGIServer(("127.0.0.1", 8080), app,
handler_class=WebSocketHandler)
server.serve_forever()