Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: b37a2aab05
Fetching contributors…

Cannot retrieve contributors at this time

executable file 137 lines (134 sloc) 4.229 kb
#!/usr/bin/env python
from SocketServer import ThreadingMixIn
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse
import urllib2
from UserList import *
from MessageList import *
from ErrorCodes import Error
import json
messages = Messages();
users = Users();
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
'''def __init__(self, a, b):
self.APIlist = [];
HTTPServer.__init__(self, a, b);'''
def hookup(self, paths, func):
self.APIlist.append([paths, func]);
# I don't like pythons parse_qs.
def parse_qs(str):
s = str.split('&');
dict = {};
for x in s:
name, sep, value = x.partition('=')
dict[name] = urllib2.unquote(value)
return dict
def d2j(dict, callback=None):
str = json.dumps(dict);
if callback != None:
return ''.join([callback,"(",str, ")"]);
return str
class ChatHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsedPath = urlparse.urlparse(self.path);
query = parse_qs(parsedPath.query);
result = "uhhh.... 404?";
for l in server.APIlist:
if parsedPath.path in l[0]:
result = l[1](query)
self.wfile.write(result);
def is_number(num):
try:
int(num);
except:
return False;
else:
return True
def login(params):
result = {"success": True}
try:
id = users.addUser(params.get("nick",""));
except Exception as e:
errorCode = e[0]
result["success"] = False
if errorCode == Error.USER_TAKEN:
result["message"] = "Username taken!"
elif errorCode == Error.USER_INVALID:
result["message"] = "Username is invalid!";
elif errorCode == Error.USER_RESERVED:
result["message"] = "That username is reserved";
result["code"] = errorCode
else:
result["data"] = users[id];
result["id"] = id
return d2j(result, params.get("callback", None));
def post_message(params):
result = {"success": True};
uid = params.get("uid", None);
message=params.get("message", "");
room = params.get("room", "lobby");
if uid in users:
users[uid].activity();
messages.addMessage(users[uid]["nick"], message, room);
else:
result["success"] = false;
return d2j(result, params.get("callback", None));
def get_messages(params):
result = {"success": False};
uid = params.get("uid","")
timeout = params.get("timeout", "20");
since = params.get("since", 0);
if uid in users:
users[uid].activity();
if is_number(since) == False:
result["message"] = "Since needs to be a number"
elif uid not in users:
result["message"] = "User doesn't exist";
elif timeout.isdigit() == False:
result["message"] = "Invalid timeout"
else:
result["success"] = True
rooms = users[uid]["rooms"]
t = time.time();
timeout = int(timeout)
since = int(since)
l = len(rooms)
while time.time() - t < timeout and len(messages.get_messages(rooms)[since:]) == 0 and l == len(users[uid]["rooms"]):
pass
result["messages"] = messages.get_messages(rooms)[since:];
result["users"] = [users[user]["nick"] for user in users]
result["rooms"] = rooms;
return d2j(result, params.get("callback", None));
def join_room(params):
result = {"success": True}
uid = params.get("uid");
room = params.get("room", "")
if uid in users and room.isalnum():
users[uid].activity();
users[uid].join_room(params["room"])
messages.addMessage("system", "%s joined %s"%(users[uid]["nick"], room), room);
else:
result["success"] = False
result["message"] = "Couldn't join room!"
return d2j(result, params.get("callback", None))
def user_info(params):
result = {"success": True};
uid = params.get("uid",None)
if uid in users:
result["data"] = users[uid]
else:
result["success"] = False
result["message"] = "User Doesn't exist!"
return d2j(result, params.get("callback", None))
def template(params):
result = {"success": True};
return d2j(result, params.get("callback", None));
if __name__ == "__main__":
server = ThreadedHTTPServer(('',8081), ChatHTTPRequestHandler);
server.APIlist = [];
server.hookup(['/api/new_user'], login);
server.hookup(['/api/get_messages'], get_messages);
server.hookup(['/api/post_message'], post_message);
server.hookup(['/api/user_info'], user_info);
server.hookup(['/api/join_room'], join_room);
server.serve_forever();
Jump to Line
Something went wrong with that request. Please try again.