def run(self): if self.resource == 'reserved': raise(errors.UnimplementedError) if self.method == 'get': raw_records = self.site.get_relations(self.type, self.name, self.tgt_type, self.tgt_name, self.resource) records = [{'timestamp':[xmlext.convert_datetime(record[0])], 'value':[record[1]]} for record in raw_records] treexml.insert_node(self.response, 'history', {'num_records':[repr(len(records))], 'record':records}) prediction = self.site.get_naive_pred(self.tgt_type, self.tgt_name, self.resource) treexml.insert_node(self.response, 'prediction', {'value':[repr(prediction)]}) else: # self.method == 'post': try: (root, doc) = treexml.decode(self.data) value = doc['value'][0] except treexml.DecodeError: try: value = float(self.data) except ValueError: raise(errors.PostError) self.site.insert_relation(self.type, self.name, self.tgt_type, self.tgt_name, self.resource, value)
def run(self): if self.method == 'post': # posting metadata for this object value = self.data tag = self.resource self.site.insert_meta(self.type, self.name, tag, value) elif self.resource.startswith('rec'): recstr = self.resource.lstrip('rec') target_type = '' num_recs = 0 if recstr.startswith('-one-'): target_type = recstr.lstrip('-one-') num_recs = 1 elif re.search('^-(item|user)s$', recstr): target_type = re.findall('^-(item|user)s$', recstr)[0] #treexml.insert_node(self.response, 'debug', self.query) try: num_recs = int(self.query['num'][0]) except: num_recs = 10 recids = self.site.get_recs(self.type, self.name, target_type, '', num_recs) recs = [] rank = 0 for recid in recids: rank += 1 recs.append({'rank':repr(rank), target_type:[{'id':recid}]}) treexml.insert_node(self.response, 'recommendations', {'rec':recs})
def runTest(self): req = {} treexml.insert_node(req, 'value', '5.0') reqxml = treexml.encode('request', req) (root, resp) = treexml.decode(self.conn.post('/users/bob/items/teacup/rating', reqxml)) self.assertEqual(resp['status'][0]['type'][0], 'OKAY') (root, resp) = treexml.decode(self.conn.post('/users/bob/items/teacup/rating', '3')) self.assertEqual(resp['status'][0]['type'][0], 'OKAY') (root, resp) = treexml.decode(self.conn.post('/users/sally/items/teacup/rating', '2')) self.assertEqual(resp['status'][0]['type'][0], 'OKAY') (root, resp) = treexml.decode(self.conn.post('/users/john/items/teacup/rating', '4')) self.assertEqual(resp['status'][0]['type'][0], 'OKAY') (root, resp) = treexml.decode(self.conn.get('/users/bob/items/teacup/rating')) #self.assertEqual(len(resp['history'][0]['record']), 2) #self.assertEqual(resp['history'][0]['record'][0]['value'][0], '3.0') #self.assertEqual(resp['history'][0]['record'][1]['value'][0], '5.0') #self.assertEqual(resp['prediction'][0]['value'][0], '3.5') (root, resp) = treexml.decode(self.conn.get('/users/sally/items/teacup/rating')) self.assertEqual(len(resp['history'][0]['record']), 1) self.assertEqual(resp['history'][0]['record'][0]['value'][0], '2') #self.assertEqual(resp['prediction'][0]['value'][0], '3.5') (root, resp) = treexml.decode(self.conn.get('/users/sally/items/nonexist/rating')) #self.assertEqual(resp['prediction'][0]['value'][0], '0.0') self.assertEqual(resp['history'][0]['num_records'][0], '0') (root, resp) = treexml.decode(self.conn.post('/users/john/items/basket/rating', '1')) self.assertEqual(resp['status'][0]['type'][0], 'OKAY') (root, resp) = treexml.decode(self.conn.get('/users')) self.assertEqual(resp['userlist'][0]['id'][0], 'bob') self.assertEqual(resp['userlist'][0]['id'][1], 'john') self.assertEqual(resp['userlist'][0]['id'][2], 'sally') self.assertEqual(len(resp['userlist'][0]['id']), 3)
def run(self): if self.method == 'get': meta = self.site.get_meta(self.type, self.name) treexml.insert_node(self.response[self.type][0], 'meta', meta) else: # self.method == 'post' (root, req) = treexml.decode(self.data) if 'meta' in req: meta = req['meta'][0] for tag in meta: self.site.insert_meta(self.type, self.name, tag, meta[tag][0])
def runTest(self): req = {} tags = {'name':'Bob', 'phone':'123-456-7890'} treexml.insert_node(req, 'meta', tags) reqxml = treexml.encode('request', req) (root, resp) = treexml.decode(self.conn.post('/users/bob', reqxml)) self.assertEqual(resp['status'][0]['type'][0], 'OKAY') (root, resp) = treexml.decode(self.conn.get('/users/bob')) self.assertEqual(len(resp['user'][0]['meta'][0]), 2) self.assertEqual(resp['user'][0]['meta'][0]['phone'][0], '123-456-7890') self.assertEqual(resp['user'][0]['meta'][0]['name'][0], 'Bob') (root, resp) = treexml.decode(self.conn.post('/users/john/name', 'John')) (root, resp) = treexml.decode(self.conn.post('/users/sally/name', 'Sally')) (root, resp) = treexml.decode(self.conn.get('/users')) self.assertEqual(resp['userlist'][0]['id'][0], 'bob') self.assertEqual(resp['userlist'][0]['id'][1], 'john') self.assertEqual(resp['userlist'][0]['id'][2], 'sally') self.assertEqual(len(resp['userlist'][0]['id']), 3)
def __init__(self, site, response, method, query, args): self.site = site self.response = response self.method = method self.query = query self.type = None self.name = None self.tgt_type = None self.tgt_name = None self.resource = None for arg in args: val = args[arg] # There must be an elegant way to do this if arg == 'type': self.type = val elif arg == 'name': self.name = val elif arg == 'tgt_type': self.tgt_type = val elif arg == 'tgt_name': self.tgt_name = val elif arg == 'resource': self.resource = val elif arg == 'postdata': self.data = val if self.type and self.name: treexml.insert_node(self.response, self.type, {'id':[self.name]}) if self.tgt_type and self.tgt_name: treexml.insert_node(self.response, 'target_%s' % self.tgt_type, {'id':[self.tgt_name]}) #if self.resource: # treexml.insert_node(self.response, 'resource', {'id':[self.resource]}) if self.name: if not self.type: raise(errors.UnknownError) try: self.name = filters.check_identifier(self.name, 32) except filters.Error: raise(errors.IdError) if self.tgt_name: if not self.tgt_type: raise(errors.UnknownError) try: self.tgt_name = filters.check_identifier(self.tgt_name, 32) except filters.Error: raise(errors.IdError)
#!/usr/bin/env python import treexml if __name__ == '__main__': xml = ('<?xml version="1.0" ?><response><status><type>\nOKAY\n</type>' + '<desc>Everything is just fine.</desc></status><empty/>' + '<time>2:08 AM</time><time>5:43 PM</time></response>') (root, doc) = treexml.decode(xml) print '\'%s\': %s' % (root, doc) print doc['status'][0]['desc'][0] print 'times: %s' % ', '.join(doc['time']) print treexml.encode(root, doc) print treexml.encode(root, doc['status'][0]) r = {} print r msg = treexml.insert_node(r, 'message', {'text':['hello'],'language':['english']}) print r #treexml.insert_node(r['message'], 'language', 'english') #print r print treexml.encode(root, r)
def debug(self, text): treexml.insert_node(self.response, 'debug', str(text))
def run(self): objs = self.site.get_objects(self.type) treexml.insert_node(self.response, '%slist' % self.type, {'id':objs})
def run(self): processing_start_time = time.time() self.root = "response" self.response = {} if not self.headers: return self.failure("Header 'host' required for all requests.") hostname = self.headers["host"].partition(":")[0] hostname_matches = re.findall("(\w+).(rapidrec.com|localhost)", hostname) if not hostname_matches: return self.failure( "Could not determine sitename. Please use " + "[sitename].rapidrec.com for all requests." ) else: self.sitename = hostname_matches[0][0] # Check the validity of the sitename try: self.sitename = filters.check_name(self.sitename, 32) except (filters.TypeError, filters.RangeError): return self.failure("Invalid site: %s" % self.sitename) # Check that the site exists by instantiating RapidRecSite try: rrsite = RapidRecSite(self.sitename) except RapidRecSite.ConnectionError: return self.failure("Unknown site: %s" % self.sitename) # Check the remote IP against the list of allowed IPs remoteip = self.request.getClientIP() # Break a comma-separated string into a list, with one tuple per IP ('IP', unused, 'cidr') try: iplist = str(rrsite.get_config_field("ip_allow")).split(",") except RapidRecSite.ConfigFieldNotFound: iplist = ["0.0.0.0/0"] while "" in iplist: iplist.remove("") iplist.append("127.0.0.1") if self.sitename.startswith("test"): iplist.append("68.9.232.69") # for development only if not ipfilter.is_ip_in_list(remoteip, iplist): return self.failure("Access forbidden from your IP: %s is not in { %s }" % (remoteip, ", ".join(iplist))) # At this point, the request is considered authentic. # We now proceed to process the request. # Find the path list and query (if any) by breaking up the QUERY_STRING # (fullpath, unused, query) = self.path.partition('?') fullpath = self.path path = fullpath.split("/") # Remove empty strings from the path list caused # by duplicate and unnecessary slashes in the path while "" in path: path.remove("") depth = 0 args = {} if self.method == "post": if "content-length" not in self.headers: return self.failure("content-length required when POSTing") self.contentLength = int(self.headers["content-length"]) self.request.content.seek(0, 0) args["postdata"] = self.request.content.read(self.contentLength) elif self.method != "get": return self.failure("Method not supported. Only GET and POST operations are allowed.") objtypes = ["users", "items", "movies"] try: if len(path) <= depth: raise (res.errors.UnimplementedError) elif path[depth] == "config": # /config... depth += 1 raise (res.errors.UnimplementedError) elif path[depth] in objtypes: # /objs... args["type"] = "user" if path[depth] == "users" else "item" depth += 1 if len(path) <= depth: # /objs Handler = res.objs.Handler else: # /objs/{obj}... args["name"] = path[depth] depth += 1 if len(path) <= depth: # /objs/{obj} Handler = res.obj.Handler elif path[depth] in objtypes: # /objs/{obj}/objs... args["tgt_type"] = "user" if path[depth] == "users" else "item" depth += 1 if len(path) <= depth: # /objs/{obj}/objs raise (res.errors.UnimplementedError) else: # /objs/{obj}/objs/{obj}... args["tgt_name"] = path[depth] depth += 1 if len(path) <= depth: # /objs/{obj}/objs/{obj} Handler = res.objobj.Handler else: # /objs/{obj}/objs/{obj}/{resource}... args["resource"] = path[depth] depth += 1 if len(path) <= depth: # /objs/{obj}/objs/{obj}/{resource} Handler = res.objobjres.Handler else: # /objs/{obj}/objs/{obj}/{resource}/... raise (res.errors.UnsupportedError) else: # /objs/{obj}/resource args["resource"] = path[depth] depth += 1 if len(path) <= depth: # /objs/{obj}/{resource} Handler = res.objres.Handler else: # /objs/{obj}/{resource}/... raise (res.errors.UnsupportedError) else: # /{not-supported}... raise (res.errors.UnsupportedError) # Here is where we actually service queries that look valid so far handler = Handler(rrsite, self.response, self.method, self.request.args, args) handler.run() xmlext.set_status(self.response, "OKAY", "Query completed successfully.") except res.errors.ContentLengthMissingError: xmlext.set_status(self.response, "ERROR", "Content-length missing.") except res.errors.MethodError: xmlext.set_status(self.response, "ERROR", "Method not supported.") except res.errors.QueryError: xmlext.set_status(self.response, "ERROR", "Invalid query.") except res.errors.UnsupportedError: xmlext.set_status(self.response, "ERROR", "Resource not supported.") except res.errors.UnimplementedError: xmlext.set_status(self.response, "ERROR", "Resource not implemented.") except res.errors.PostError: xmlext.set_status(self.response, "ERROR", "Could not understand request body.") except res.errors.IdError: xmlext.set_status(self.response, "ERROR", "Invalid user or item identifier.") except res.errors.UnknownError: xmlext.set_status(self.response, "ERROR", "Unknown Error.") processing_finish_time = time.time() processing_time_elapsed = processing_finish_time - processing_start_time treexml.insert_node(self.response, "system_usage", "%f" % processing_time_elapsed) # print response self.respXML() self.send(treexml.encode(self.root, self.response)) return self.finishreq()
def set_status(response, type, desc): if 'status' not in response: treexml.insert_node(response, 'status', {'type':[''], 'desc':['']}) response['status'][0]['type'][0] = type response['status'][0]['desc'][0] = desc
def do_POST(self): if 'Content-length' not in self.headers: self.send_response(411) return; self.method = 'POST' self.resource = self.path contentLength = int(self.headers['Content-length']) reqxml = self.rfile.read(contentLength) (root, req) = treexml.decode(reqxml) data = req['data'][0] resp = {} startMoney = int(float(data['startMoney'][0])) endMoney = int(float(data['endMoney'][0])) startScore = int(float(data['startScore'][0])) endScore = int(float(data['endScore'][0])) startFrame = int(float(data['startFrame'][0])) endFrame = int(float(data['endFrame'][0])) sessionID = int(float(req['sessionID'][0])) gameNum = int(float(req['game'][0]['num'][0])) gamediff = int(float(req['game'][0]['diff'][0])) userName = req['id'][0]['name'][0] userGroup = req['id'][0]['group'][0] if userName == '': userName = '******' if userGroup == '': userGroup = 'River People' self.connect() valid_ipstr = self.conn.getone("SELECT ip FROM session_ip WHERE session_id = %s", (sessionID,)) if not valid_ipstr: self.conn.query("INSERT INTO session_ip SET ip = %s, username = %s, usergroup = %s, session_id = %s", (self.get_client_ip(), userName, userGroup, sessionID)) sessionID = self.conn.lastid() treexml.insert_node(resp, 'sessionID', str(sessionID)) else: self.conn.query("UPDATE session_ip SET username = %s, usergroup = %s WHERE session_id = %s", (userName, userGroup, sessionID)) #elif self.get_client_ip() != int(valid_ipstr): # self.path = '/bad_session_number' # self.respOK() # #print 'Session IP mismatch, session %s does not belong to %s' % (sessionID, self.get_client_ip()) # return self.conn.query(("INSERT INTO scores " + "SET session_id = %s, " + " game_num = %s, " + " game_type = %s, " + " score = %s, " + " score_delta = %s, " + " max_frame = %s, " + " start_time = CURRENT_TIMESTAMP " + "ON DUPLICATE KEY UPDATE " + " score_delta = IF(%s - score > score_delta, %s - score, score_delta), " + " score = %s, " + " max_frame = %s"), (sessionID, gameNum, gamediff, endScore, endScore, endFrame, endScore, endScore, endScore, endFrame)) game_id = self.conn.getone("SELECT id FROM scores WHERE session_id = %s AND game_num = %s", (sessionID, gameNum)) #print 'game id: %s, session id: %s, game num: %s' % (game_id, sessionID, gameNum) myrank = int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s AND score > %s AND score > 100", (gamediff, endScore))) + 1 numranks = max(1, int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s AND score > 100", (gamediff,)))) if data.has_key('frame'): for frame in data['frame']: id = int(frame['id'][0]) if frame.has_key('buildGun'): for rec in frame['buildGun']: type = int(rec['type'][0]) self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, build = 1 " + "ON DUPLICATE KEY UPDATE build = build + 1", (game_id, type)) if frame.has_key('upGun'): for rec in frame['upGun']: type = int(rec['type'][0]) self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, upgrade = 1 " + "ON DUPLICATE KEY UPDATE upgrade = upgrade + 1", (game_id, type)) if frame.has_key('sellGun'): for rec in frame['sellGun']: type = int(rec['type'][0]) self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, sell = 1 " + "ON DUPLICATE KEY UPDATE sell = sell + 1", (game_id, type)) self.conn.query("INSERT INTO replay SET game_id = %s, start_frame = %s, xml = %s", (game_id, startFrame, treexml.encode('data', data, None))) treexml.insert_node(resp, 'rank', str(myrank)) percentile = max(1, min(99, 100.0 * (numranks - myrank) / numranks)) treexml.insert_node(resp, 'percentile', '%.0f' % percentile) treexml.insert_node(resp, 'numplayers', str(self.get_num_online())) treexml.insert_node(resp, 'numspectators', '0') self.respOK() self.wfile.write(treexml.encode('rdresp', resp)) self.conn.close()
def do_GET(self): self.connect() resp = {} if (self.path == '/crossdomain.xml'): self.respOK() self.wfile.write('<?xml version="1.0" ?><cross-domain-policy><allow-access-from domain="*" to-ports="3456" /><site-control permitted-cross-domain-policies="master-only" /></cross-domain-policy>\0'); return if (self.path.startswith('/funstats')): self.respHTML() self.path = '/funstats' global funFacts self.wfile.write('%s' % funFacts) return if (self.path.startswith('/highscores')): self.respHTML() self.wfile.write(open('highscores.html', 'r').read()) return if (self.path.startswith('/highscore.xsl')): self.respOK() self.wfile.write(open('highscore.xsl', 'r').read()) return if (self.path.startswith('/dojo.js')): self.respJS() self.wfile.write(open('dojo.js', 'r').read()) return if (self.path.startswith('/sessionID')): self.path = '/sessionID' self.conn.query("INSERT into session_ip SET ip = %s, username = '******', usergroup = 'River People'", (self.get_client_ip(),)) treexml.insert_node(resp, 'sessionID', str(self.conn.lastid())) treexml.insert_node(resp, 'numplayers', str(self.get_num_online())) if (self.path.startswith('/randgame')): self.path = '/randgame' game_id = int(self.conn.getone('SELECT DISTINCT(game_id) FROM replay WHERE start_frame > 1800 AND TIMESTAMPDIFF(SECOND, timestamp, NOW()) < 3600 ORDER BY RAND() LIMIT 1')) treexml.insert_node(resp, 'gameID', str(game_id)) treexml.insert_node(resp, 'difficulty', str(self.conn.getone("SELECT game_type FROM scores WHERE id = %s", (game_id,)))) sessionID = self.conn.getone("SELECT session_id FROM scores WHERE id = %s", (game_id,)) treexml.insert_node(resp, 'username', self.conn.getone("SELECT username FROM session_ip WHERE session_id = %s", (sessionID,))) treexml.insert_node(resp, 'usergroup', self.conn.getone("SELECT usergroup FROM session_ip WHERE session_id = %s", (sessionID,))) treexml.insert_node(resp, 'minutesago', str(self.conn.getone("SELECT timestampdiff(MINUTE, start_time, now()) FROM scores WHERE id = %s", (game_id,)))) if (self.path.startswith('/hs')): category = self.path.split('/')[2] name = self.path.split('/')[3] type = self.path.split('/')[4] timestr = self.path.split('/')[5] offset = int(self.path.split('/')[6]) num = int(self.path.split('/')[7]) if timestr == 'week': seconds = 86400 * 7 elif timestr == 'day': seconds = 86400 elif timestr == 'hour': seconds = 3600 else: seconds = 2000000000 if category == 'self': qualifier = "WHERE session_ip.username = %s" elif category == 'group': qualifier = "WHERE session_ip.usergroup = %s" else: qualifier = "WHERE %s != 'dkjfhdskfjhdf'" rows = self.conn.getrows(("SELECT session_ip.username AS name, session_ip.usergroup AS gruppe, scores.score AS score, " + "start_time AS time FROM scores JOIN session_ip ON (session_ip.session_id = scores.session_id) " + qualifier + " AND scores.game_type = %s AND TIMESTAMPDIFF(SECOND, start_time, now()) < %s ORDER BY scores.score DESC LIMIT %s OFFSET %s"), (name, type, seconds, num, offset)) data = [{'name':[row['name']], 'group':[row['gruppe']], 'score':[str(row['score'])], 'time':[row['time'].ctime()]} for row in rows] for row in data: row['rank'] = [str(offset)] offset += 1 for row in data: treexml.insert_node(resp, 'ranking', row) if (self.path.startswith('/replay')): game_id = int(self.path.split('/')[2]) frame_num = int(self.path.split('/')[3]) self.path = '/replay' frame = self.conn.getone('SELECT xml FROM replay WHERE game_id = %s AND start_frame = %s', (game_id, frame_num)) if frame: treexml.insert_node(resp, 'available', 'yes') treexml.insert_node(resp, 'replay', frame) else: treexml.insert_node(resp, 'available', 'no') treexml.insert_node(resp, 'numplayers', str(self.get_num_online())) self.respOK() self.wfile.write(treexml.encode('rdresp', resp)) self.conn.close()
def render_POST(self, request): self.startreq(request, 'POST') if 'content-length' not in self.headers: return ''; contentLength = int(self.headers['content-length']) request.content.seek(0, 0) reqxml = request.content.read(contentLength) (root, req) = treexml.decode(reqxml) data = req['data'][0] resp = {} startMoney = int(float(data['startMoney'][0])) endMoney = int(float(data['endMoney'][0])) startScore = int(float(data['startScore'][0])) endScore = int(float(data['endScore'][0])) startFrame = int(float(data['startFrame'][0])) endFrame = int(float(data['endFrame'][0])) sessionID = int(float(req['sessionID'][0])) gameNum = int(float(req['game'][0]['num'][0])) gamediff = int(float(req['game'][0]['diff'][0])) userName = req['id'][0]['name'][0] userGroup = req['id'][0]['group'][0] if userName == '': userName = '******' if userGroup == '': userGroup = 'River People' valid_ipstr = self.conn.getone("SELECT ip FROM session_ip WHERE session_id = %s", (sessionID,)) if not valid_ipstr: self.conn.cquery("INSERT INTO session_ip SET ip = %s, username = %s, usergroup = %s, session_id = %s", (self.get_client_ip(), userName, userGroup, sessionID)) sessionID = self.conn.lastid() treexml.insert_node(resp, 'sessionID', str(sessionID)) else: row = self.conn.getrow("SELECT username, usergroup FROM session_ip WHERE session_id = %s", (sessionID,)) if row['username'] != userName or row['usergroup'] != userGroup: self.conn.cquery("UPDATE session_ip SET username = %s, usergroup = %s WHERE session_id = %s", (userName, userGroup, sessionID)) #elif self.get_client_ip() != int(valid_ipstr): # self.path = '/bad_session_number' # self.respOK() # #print 'Session IP mismatch, session %s does not belong to %s' % (sessionID, self.get_client_ip()) # return row = self.conn.getrow("SELECT id, score, score_delta FROM scores WHERE session_id = %s AND game_num = %s", (sessionID, gameNum)) if not row: self.conn.cquery(("INSERT INTO scores " + "SET session_id = %s, " + " game_num = %s, " + " game_type = %s, " + " score = %s, " + " score_delta = %s, " + " max_frame = %s, " + " start_time = CURRENT_TIMESTAMP "), (sessionID, gameNum, gamediff, endScore, endScore, endFrame)) game_id = self.conn.lastid() else: game_id = row['id'] lastScore = row['score'] scoreDelta = row['score_delta'] scoreDelta = max(scoreDelta, endScore - lastScore) self.conn.cquery(("UPDATE scores " + "SET score_delta = %s, " + " score = %s, " + " max_frame = %s " + "WHERE id = %s"), (scoreDelta, endScore, endFrame, game_id)) #print 'game id: %s, session id: %s, game num: %s' % (game_id, sessionID, gameNum) #myrank = int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s AND score > %s", (gamediff, endScore))) + 1 #numranks = max(1, int(self.conn.getone("SELECT COUNT(*) FROM scores WHERE game_type = %s", (gamediff,)))) (myrank, numranks) = getMyRankAndNumRanks(gamediff, endScore) if data.has_key('frame'): for frame in data['frame']: id = int(frame['id'][0]) if frame.has_key('buildGun'): for rec in frame['buildGun']: type = int(rec['type'][0]) self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, build = 1 " + "ON DUPLICATE KEY UPDATE build = build + 1", (game_id, type)) if frame.has_key('upGun'): for rec in frame['upGun']: type = int(rec['type'][0]) self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, upgrade = 1 " + "ON DUPLICATE KEY UPDATE upgrade = upgrade + 1", (game_id, type)) if frame.has_key('sellGun'): for rec in frame['sellGun']: type = int(rec['type'][0]) self.conn.query("INSERT INTO guns SET game_id = %s, type = %s, sell = 1 " + "ON DUPLICATE KEY UPDATE sell = sell + 1", (game_id, type)) self.conn.commit('guns commit') del data['startMoney'] del data['endMoney'] del data['startScore'] del data['endScore'] self.conn.cquery("INSERT INTO replay SET game_id = %s, start_frame = %s, xml = compress(%s)", (game_id, startFrame, treexml.encode('data', data, None))) treexml.insert_node(resp, 'rank', str(myrank)) percentile = max(1, min(99, 100.0 * (numranks - myrank) / numranks)) treexml.insert_node(resp, 'percentile', '%.0f' % percentile) treexml.insert_node(resp, 'numplayers', str(self.get_num_online())) treexml.insert_node(resp, 'numspectators', '0') treexml.insert_node(resp, 'gameid', str(game_id)) self.respOK() self.send(treexml.encode('rdresp', resp)) return self.finishreq()
def render_GET(self, request): self.startreq(request, 'GET') resp = {} if (self.path.startswith('/dojo') or self.path.startswith('/dijit')): self.respJS() self.send(open(self.path[1:], 'r').read()) return self.finishreq() if (self.path == '/crossdomain.xml'): self.respOK() self.send('<?xml version="1.0" ?><cross-domain-policy><allow-access-from domain="*" to-ports="3456" /><site-control permitted-cross-domain-policies="master-only" /></cross-domain-policy>\0'); return self.finishreq() elif (self.path.startswith('/funstats')): self.respHTML() self.path = '/funstats' global funFacts self.send('%s' % funFacts) return self.finishreq() elif (self.path.startswith('/highscores')): if len(self.path.split('/')) < 4: username = '******' usergroup = 'River People' else: username = self.path.split('/')[2] usergroup = self.path.split('/')[3] self.respHTML() self.send(open('highscores.html', 'r').read().replace('__USERNAME__', username).replace('__USERGROUP__', usergroup)) return self.finishreq() elif (self.path.startswith('/style.css')): self.respCSS() self.send(open('style.css', 'r').read()) return self.finishreq() elif (self.path.startswith('/dojo.js')): self.respJS() self.send(open('dojo.js', 'r').read()) return self.finishreq() elif (self.path.startswith('/sessionID')): if len(self.path.split('/')) > 2: version = self.path.split('/')[2] else: version = '100' self.path = '/sessionID/%s' % version self.conn.cquery("INSERT into session_ip SET ip = %s, version = %s, username = '******', usergroup = 'River People'", (self.get_client_ip(), int(version))) treexml.insert_node(resp, 'sessionID', str(self.conn.lastid())) treexml.insert_node(resp, 'numplayers', str(self.get_num_online())) elif (self.path.startswith('/randgame') or self.path.startswith('/playgame') or self.path.startswith('/livegame')): if self.path.startswith('/livegame'): self.path = '/livegame' game_id = int(self.conn.getone('SELECT id FROM scores WHERE max_frame > 600 AND TIMESTAMPDIFF(SECOND, end_time, NOW()) < 40 ORDER BY RAND() LIMIT 1')) if not game_id: game_id = int(self.conn.getone('SELECT id FROM scores WHERE max_frame > 1800 ORDER BY end_time DESC LIMIT 1')) elif self.path.startswith('/randgame'): self.path = '/randgame' game_id = int(self.conn.getone('SELECT id FROM scores WHERE max_frame > 1800 AND TIMESTAMPDIFF(SECOND, end_time, NOW()) < 3600 ORDER BY RAND() LIMIT 1')) else: game_id = int(self.path.split('/')[2]) self.path = '/playgame' sessionID = self.conn.getone("SELECT session_id FROM scores WHERE id = %s", (game_id,)) if not sessionID: game_id = int(self.conn.getone('SELECT id FROM scores WHERE max_frame > 1800 AND TIMESTAMPDIFF(SECOND, end_time, NOW()) < 3600 ORDER BY RAND() LIMIT 1')) sessionID = self.conn.getone("SELECT session_id FROM scores WHERE id = %s", (game_id,)) treexml.insert_node(resp, 'gameID', str(game_id)) treexml.insert_node(resp, 'difficulty', str(self.conn.getone("SELECT game_type FROM scores WHERE id = %s", (game_id,)))) treexml.insert_node(resp, 'username', self.conn.getone("SELECT username FROM session_ip WHERE session_id = %s", (sessionID,))) treexml.insert_node(resp, 'usergroup', self.conn.getone("SELECT usergroup FROM session_ip WHERE session_id = %s", (sessionID,))) treexml.insert_node(resp, 'minutesago', str(self.conn.getone("SELECT timestampdiff(MINUTE, start_time, now()) FROM scores WHERE id = %s", (game_id,)))) elif (self.path.startswith('/hs')): category = self.path.split('/')[2] name = self.path.split('/')[3] name = name.replace('%20', ' ') type = self.path.split('/')[4] timestr = self.path.split('/')[5] offset = int(self.path.split('/')[6]) num = int(self.path.split('/')[7]) self.path = '/hs' if timestr == 'week': seconds = 86400 * 7 elif timestr == 'day': seconds = 86400 elif timestr == 'hour': seconds = 3600 else: seconds = 2000000000 if category == 'self': qualifier = "WHERE session_ip.username = %s" elif category == 'group': qualifier = "WHERE session_ip.usergroup = %s" else: qualifier = "WHERE %s != 'dkjfhdskfjhdf'" rows = self.conn.getrows(("SELECT session_ip.username AS name, session_ip.usergroup AS gruppe, scores.score AS score, " + "start_time AS time, id FROM scores JOIN session_ip ON (session_ip.session_id = scores.session_id) " + qualifier + " AND scores.game_type = %s AND TIMESTAMPDIFF(SECOND, start_time, now()) < %s ORDER BY scores.score DESC LIMIT %s OFFSET %s"), (name, type, seconds, num, offset)) watchstr = '<a href="#" onClick="play(%s)">Watch</a>' data = [{'td':[row['name'], row['gruppe'], str(row['score']), row['time'].ctime(), watchstr % row['id']]} for row in rows] #for row in data: # treexml.insert_node(row, 'td', str(offset)) # offset += 1 treexml.insert_node(resp, 'tr', {'td':['Name', 'Group', 'Score', 'Time', 'Video']}) for row in data: treexml.insert_node(resp, 'tr', row) self.respHTML() self.send('<head><link rel="stylesheet" type="text/css" href="/style.css" /></head>') self.send('<body>%s</body>' % treexml.encode('table', resp, None)) return self.finishreq() elif (self.path.startswith('/replay')): game_id = int(self.path.split('/')[2]) frame_num = int(self.path.split('/')[3]) self.path = '/replay' frame = self.conn.getone('SELECT uncompress(xml) FROM replay WHERE game_id = %s AND start_frame = %s', (game_id, frame_num)) if frame: treexml.insert_node(resp, 'available', 'yes') treexml.insert_node(resp, 'replay', frame) else: treexml.insert_node(resp, 'available', 'no') treexml.insert_node(resp, 'numplayers', str(self.get_num_online())) self.respOK() self.send(treexml.encode('rdresp', resp)) return self.finishreq()