Skip to content

Commit

Permalink
Merge branch 'wsgi' of github.com:neuront/sgs into wsgi
Browse files Browse the repository at this point in the history
  • Loading branch information
zheplusplus committed Mar 4, 2012
2 parents cbf1013 + 523b0c0 commit 8883322
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 107 deletions.
52 changes: 12 additions & 40 deletions gateway/wsgi/game.py
Expand Up @@ -8,46 +8,17 @@ class GameRoom:
def __init__(self):
self.players_tokens = []
self.host = ''
self.handlers = {
'/ctrl/add': self.add_player,
'/ctrl/exit': self.player_exit,
'/ctrl/start': self.start,
'/info/status': self.game_status,
'/info/events': self.get_events,
'/info/hint': self.get_hint,
'/info/checktoken': self.check_token,
'/act': self.player_act,
}
self.game_started = False

def response(self, path, request_body):
if not path in self.handlers:
return { 'code': 404 }
try:
return self.handlers[path](request_body)
except ValueError, e:
return {
'code': ret_code.BAD_REQUEST,
'reason': e.message,
}
except KeyError, e:
return {
'code': ret_code.BAD_REQUEST,
'reason': ret_code.BR_MISSING_ARG % e.message,
}
except (NameError, SyntaxError), e:
return {
'code': ret_code.BAD_REQUEST,
'reason': 'Syntax error: %s' % e.message,
}

def check_token(self, request_body):
token = request_body['token']
return {
'code': ret_code.OK,
'in': 1 if request_body in self.players_tokens else 0,
'in': 1 if token in self.players_tokens else 0,
}

def player_exit(self, token):
def player_exit(self, request_body):
token = request_body['token']
if not token in self.players_tokens:
raise ValueError('Not joined in')
self.players_tokens.remove(token)
Expand All @@ -64,18 +35,19 @@ def _check_game_started(self):
raise ValueError('Game not started')

def game_status(self, request_body):
token = request_body['token'] if 'token' in request_body else ''
return {
'code': ret_code.OK,
'players': len(self.players_tokens),
'started': 1 if self.game_started else 0,
'host': 1 if self.host == request_body else 0,
'host': 1 if self.host == token else 0,
}

def add_player(self, request_body):
self._check_game_not_started()
if 8 == len(self.players_tokens):
raise ValueError('room full')
token = sha256(request_body + str(time.time())).hexdigest()
token = sha256(str(request_body) + str(time.time())).hexdigest()
if len(self.players_tokens) == 0:
self.host = token
self.players_tokens.append(token)
Expand All @@ -84,8 +56,9 @@ def add_player(self, request_body):
'token': token,
}

def start(self, token):
def start(self, request_body):
self._check_game_not_started()
token = request_body['token']
if len(self.players_tokens) < 2:
return {
'code': ret_code.BAD_REQUEST,
Expand All @@ -102,18 +75,17 @@ def start(self, token):

def get_hint(self, request_body):
self._check_game_started()
return self.gc.hint(request_body)
return self.gc.hint(request_body['token'])

def get_events(self, request_body):
def get_events(self, args):
self._check_game_started()
args = eval(request_body, dict(), dict())
return {
'code': 200,
'events': self.gc.get_events(args['token'],
args['previous event id']),
}

def player_act(self, request_body):
return self.gc.player_act(eval(request_body, dict(), dict()))
return self.gc.player_act(request_body)

game_room = GameRoom()
51 changes: 45 additions & 6 deletions gateway/wsgi/server.py
@@ -1,6 +1,8 @@
import os
from wsgiref.simple_server import make_server
import simplejson

import core.src.ret_code as ret_code
import game
import static_files

Expand All @@ -9,6 +11,7 @@ def start():

def plain_headers():
return [('Content-type', 'text/plain')]

RESPONSE_MAPPING = {
200: lambda sr: sr('200 OK', plain_headers()),
400: lambda sr: sr('400 Bad Request', plain_headers()),
Expand All @@ -17,16 +20,52 @@ def plain_headers():

def app(env, start_response):
path = env['PATH_INFO']
if '/' == path:
if path == '/':
start_response('200 OK', [('Content-type', 'text/html')])
return read_index()
if path.startswith('/static/'):
return static_files.serve(path[1:], start_response)
request_body_size = int(env['CONTENT_LENGTH'])
request_body = env['wsgi.input'].read(request_body_size)
response = game.game_room.response(path, request_body)
RESPONSE_MAPPING[response['code']](start_response)
return [str(response)]
if path == '/action':
request_body_size = int(env['CONTENT_LENGTH'])
request_body = env['wsgi.input'].read(request_body_size)
response = game_response(request_body)
RESPONSE_MAPPING[response['code']](start_response)
return [simplejson.dumps(response)]
RESPONSE_MAPPING[404](start_response)
return ['']

def game_response(request_body):
try:
request_body = simplejson.loads(request_body)
handlers = {
'ctrl/add': game.game_room.add_player,
'ctrl/exit': game.game_room.player_exit,
'ctrl/start': game.game_room.start,
'info/status': game.game_room.game_status,
'info/events': game.game_room.get_events,
'info/hint': game.game_room.get_hint,
'info/checktoken': game.game_room.check_token,
'act': game.game_room.player_act,
}
path = request_body['controller']
if not path in handlers:
return { 'code': 404 }
return handlers[path](request_body)
except ValueError, e:
return {
'code': ret_code.BAD_REQUEST,
'reason': e.message,
}
except KeyError, e:
return {
'code': ret_code.BAD_REQUEST,
'reason': ret_code.BR_MISSING_ARG % e.message,
}
except simplejson.decoder.JSONDecodeError, e:
return {
'code': ret_code.BAD_REQUEST,
'reason': 'Syntax error: %s' % e.message,
}

def read_index():
path = os.path.join(os.path.dirname(__file__), 'static/index.html')
Expand Down
28 changes: 13 additions & 15 deletions gateway/wsgi/static/index.html
Expand Up @@ -14,6 +14,8 @@
var events_heartbeat = null;

function post_data(data, url, onResult) {
data['token'] = token;
data['controller'] = url;
var req = null;
try {
if (window.XMLHttpRequest) {
Expand All @@ -25,18 +27,17 @@
alert('Browser not support AJAX!');
return;
}
req.open('POST', url, true);
req.open('POST', '/action', true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
onResult(eval('(' + req.responseText + ')'));
}
};
req.send(data);
req.send(JSON.stringify(data));
}

function post_act(data) {
data['token'] = token;
return post_data(JSON.stringify(data), '/act', function(result) {
return post_data(data, 'act', function(result) {
if (result['code'] != 200) {
crit('SEND:' + JSON.stringify(data));
crit('REASON:' + result['reason']);
Expand All @@ -54,7 +55,7 @@
var token = localStorage.getItem('token');

function joinGame() {
post_data('', '/ctrl/add', function(result) {
post_data({}, 'ctrl/add', function(result) {
if (result['code'] == 200) {
token = result['token'];
localStorage.setItem('token', token);
Expand All @@ -79,15 +80,15 @@
function exitGame() {
joinPane.style.visibility = 'visible';
startPane.style.visibility = 'hidden';
post_data(token, '/ctrl/exit', function(r) {});
post_data({}, 'ctrl/exit', function(r) {});
token = null;
clearTimeout(status_heartbeat);
clearTimeout(hint_heartbeat);
clearTimeout(events_heartbeat);
}

function startGame() {
post_data(token, '/ctrl/start', function(result) {
post_data({}, 'ctrl/start', function(result) {
if (result['code'] == 200) {
started();
} else {
Expand All @@ -97,7 +98,7 @@
}

function getStatus() {
post_data(token, '/info/status', function(result) {
post_data({}, 'info/status', function(result) {
if (result['started'] == 0) {
updateRoomPlayers(result['players'], result['host']);
status_heartbeat = setTimeout(enter, BEAT_INTERVAL);
Expand All @@ -108,18 +109,15 @@
}

function getEvents() {
var request_body = {
'token': token,
'previous event id': eventlist.prevId(),
};
post_data(JSON.stringify(request_body), '/info/events', function(result) {
post_data({ 'previous event id': eventlist.prevId() }, 'info/events',
function(result) {
eventlist.append(result, game);
events_heartbeat = setTimeout(getEvents, BEAT_INTERVAL);
});
}

function getHint() {
post_data(token, '/info/hint', function(result) {
post_data({}, 'info/hint', function(result) {
game.hint(result);
hint_heartbeat = setTimeout(getHint, BEAT_INTERVAL);
});
Expand Down Expand Up @@ -149,7 +147,7 @@

game = new Game(gamePane);

post_data(token, '/info/checktoken', function(result) {
post_data({}, 'info/checktoken', function(result) {
if (result['in'] == 1) {
enter();
}
Expand Down

0 comments on commit 8883322

Please sign in to comment.