Implemented ability to fetch all messages since last check.
Implemented ability to fetch all messages since last check.

If you setup a room and stage some messages with the following:

# Create Room
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"createRoom","payload":"{\"roomName\":\"BenTest\",\"owner\":\"ben\",\"passhash\":\"abcdefg\"}"}'

# Subscribe User
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"inviteUser","payload":"{\"roomName\":\"BenTest\",\"user\":\"ben2\"}"}'

# Send a message
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"sendMsg","payload":"{\"roomName\":\"BenTest\", \"msg\":\"ENCRYPTED-DATA\",\"user\":\"ben2\"}"}'

# Send another
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"sendMsg","payload":"{\"roomName\":\"BenTest\", \"msg\":\"ENCRYPTED-DATA2\",\"user\":\"ben2\"}"}'

You can then fetch those messages with the following call

curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"pollMsg","payload":"{\"roomName\":\"BenTest\", \"mylast\":0,\"user\":\"ben2\"}"}'

This means we now have the basic components in place:

* Rooms can be created
* Users can be subscribed to the room
* Messages can be sent
* Clients can check for updated messages

Course, there's no auth yet, but it's probably better to try and build a working client first (as debugging is easier without a complex auth system in the way)

#!/usr/bin/env python #!/usr/bin/env python
# #
# #
# LocalChat Server Script # LocalChat Server Script
# #
# #
# apt-get install: # apt-get install:
# python-flask # python-flask
# #
   
from flask import Flask from flask import Flask
from flask import request, make_response from flask import request, make_response
   
   
   
import sqlite3 import sqlite3
import time import time
import os import os
import json import json
   
app = Flask(__name__) app = Flask(__name__)
   
   
   
@app.route('/', defaults={'path': ''},methods=["POST"]) @app.route('/', defaults={'path': ''},methods=["POST"])
@app.route('/<path:path>',methods=["POST"]) @app.route('/<path:path>',methods=["POST"])
def index(path): def index(path):
print "%.6f Request start" % (time.time()) # DEBUGONLY print "%.6f Request start" % (time.time()) # DEBUGONLY
reqdata = request.get_data() reqdata = request.get_data()
try: try:
reqjson = json.loads(reqdata) reqjson = json.loads(reqdata)
except: except:
return make_response("",400) return make_response("",400)
a = msghandler.processSubmission(reqjson) a = msghandler.processSubmission(reqjson)
# Check the status # Check the status
if a in [400,403]: if a in [400,403]:
response = make_response("",a) response = make_response("",a)
return response return response
return json.dumps(a) return json.dumps(a)
   
   
   
class MsgHandler(object): class MsgHandler(object):
   
   
def __init__(self): def __init__(self):
self.conn = False self.conn = False
self.cursor = False self.cursor = False
   
   
   
def createDB(self): def createDB(self):
''' Create the in-memory database ready for use ''' Create the in-memory database ready for use
''' '''
self.conn = sqlite3.connect(':memory:') self.conn = sqlite3.connect(':memory:')
self.cursor = self.conn.cursor() self.cursor = self.conn.cursor()
sql = """ CREATE TABLE rooms ( sql = """ CREATE TABLE rooms (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE, name TEXT NOT NULL UNIQUE,
owner TEXT NOT NULL, owner TEXT NOT NULL,
pass TEXT NOT NULL pass TEXT NOT NULL
); );
CREATE TABLE messages ( CREATE TABLE messages (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
ts INTEGER NOT NULL, ts INTEGER NOT NULL,
room INTEGER NOT NULL, room INTEGER NOT NULL,
msg TEXT NOT NULL msg TEXT NOT NULL
); );
CREATE TABLE users ( CREATE TABLE users (
username TEXT NOT NULL, username TEXT NOT NULL,
room INTEGER NOT NULL, room INTEGER NOT NULL,
PRIMARY KEY (username,room) PRIMARY KEY (username,room)
); );
""" """
self.conn.executescript(sql) self.conn.executescript(sql)
   
   
   
def processSubmission(self,reqjson): def processSubmission(self,reqjson):
''' Process an incoming request and route it to ''' Process an incoming request and route it to
the correct function the correct function
''' '''
if not self.conn or not self.cursor: if not self.conn or not self.cursor:
self.createDB() self.createDB()
print reqjson print reqjson
if "action" not in reqjson or "payload" not in reqjson: if "action" not in reqjson or "payload" not in reqjson:
return 400 return 400
# Decrypt the payload # Decrypt the payload
reqjson['payload'] = self.decrypt(reqjson['payload']) reqjson['payload'] = self.decrypt(reqjson['payload'])
try: try:
reqjson['payload'] = json.loads(reqjson['payload']) reqjson['payload'] = json.loads(reqjson['payload'])
except: except:
return 400 return 400
if reqjson['action'] == "createRoom": if reqjson['action'] == "createRoom":
return self.createRoom(reqjson) return self.createRoom(reqjson)
elif reqjson['action'] == "inviteUser": elif reqjson['action'] == "inviteUser":
return self.inviteUser(reqjson) return self.inviteUser(reqjson)
elif reqjson['action'] == 'sendMsg': elif reqjson['action'] == 'sendMsg':
print "Send message"  
return self.sendMsg(reqjson) return self.sendMsg(reqjson)
  elif reqjson['action'] == 'pollMsg':
  return self.fetchMsgs(reqjson)
   
   
def decrypt(self,msg): def decrypt(self,msg):
''' This is currently just a placeholder ''' This is currently just a placeholder
Will be updated later Will be updated later
''' '''
return msg return msg
   
   
   
def createRoom(self,reqjson): def createRoom(self,reqjson):
''' '''
Payload should contain a JSON object consisting of Payload should contain a JSON object consisting of
roomName roomName
owner owner
passhash passhash
e.g. e.g.
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"createRoom","payload":"{ curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"createRoom","payload":"{
\"roomName\":\"BenTest\", \"roomName\":\"BenTest\",
\"owner\":\"ben\", \"owner\":\"ben\",
\"passhash\":\"abcdefg\" \"passhash\":\"abcdefg\"
}" }"
}' }'
''' '''
print "Creating room %s" % (reqjson['payload']) print "Creating room %s" % (reqjson['payload'])
# Create a tuple for sqlite3 # Create a tuple for sqlite3
t = (reqjson['payload']['roomName'], t = (reqjson['payload']['roomName'],
reqjson['payload']['owner'], reqjson['payload']['owner'],
reqjson['payload']['passhash']) reqjson['payload']['passhash'])
try: try:
self.cursor.execute("INSERT INTO rooms (name,owner,pass) VALUES (?,?,?)",t) self.cursor.execute("INSERT INTO rooms (name,owner,pass) VALUES (?,?,?)",t)
roomid = self.cursor.lastrowid roomid = self.cursor.lastrowid
except: except:
# Probably a duplicate name, but we don't want to give the other end a reason anyway # Probably a duplicate name, but we don't want to give the other end a reason anyway
return 500 return 500
self.cursor.execute("INSERT INTO users (username,room) values (?,?)",(reqjson['payload']['owner'],roomid)) self.cursor.execute("INSERT INTO users (username,room) values (?,?)",(reqjson['payload']['owner'],roomid))
self.conn.commit() self.conn.commit()
return { return {
'status':'ok', 'status':'ok',
'roomid': roomid, 'roomid': roomid,
'name' : reqjson['payload']['roomName'] 'name' : reqjson['payload']['roomName']
} }
   
   
def inviteUser(self,reqjson): def inviteUser(self,reqjson):
''' Link a username into a room ''' Link a username into a room
   
   
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"inviteUser","payload":"{\"roomName\":\"BenTest\",\"user\":\"ben2\"}"}' curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"inviteUser","payload":"{\"roomName\":\"BenTest\",\"user\":\"ben2\"}"}'
   
''' '''
if "roomName" not in reqjson['payload']: if "roomName" not in reqjson['payload']:
return 400 return 400
room = self.getRoomID(reqjson['payload']["roomName"]) room = self.getRoomID(reqjson['payload']["roomName"])
if not room: if not room:
return 400 return 400
# Otherwise, link the user in # Otherwise, link the user in
self.cursor.execute("INSERT INTO users (username,room) values (?,?)",(reqjson['payload']['user'],room)) self.cursor.execute("INSERT INTO users (username,room) values (?,?)",(reqjson['payload']['user'],room))
self.conn.commit() self.conn.commit()
return { return {
"status":'ok' "status":'ok'
} }
def sendMsg(self,reqjson): def sendMsg(self,reqjson):
''' Push a message into a room ''' Push a message into a room
curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"sendMsg","payload":"{\"roomName\":\"BenTest\", \"msg\":\"ENCRYPTED-DATA\",\"user\":\"ben2\"}"}' curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"sendMsg","payload":"{\"roomName\":\"BenTest\", \"msg\":\"ENCRYPTED-DATA\",\"user\":\"ben2\"}"}'
''' '''
print reqjson if not self.validateUser(reqjson['payload']):
if "user" not in reqjson['payload'] or not self.validateUser(reqjson['payload']):  
return 403 return 403
if "roomName" not in reqjson['payload'] or "msg" not in reqjson['payload']: if "roomName" not in reqjson['payload'] or "msg" not in reqjson['payload']:
return 400 return 400
room = self.getRoomID(reqjson['payload']["roomName"]) room = self.getRoomID(reqjson['payload']["roomName"])
print room print room
if not room: if not room:
return 400 return 400
   
self.cursor.execute("INSERT INTO messages (ts,room,msg) VALUES (?,?,?)",(time.time(),room,reqjson['payload']['msg'])) self.cursor.execute("INSERT INTO messages (ts,room,msg) VALUES (?,?,?)",(time.time(),room,reqjson['payload']['msg']))
msgid = self.cursor.lastrowid msgid = self.cursor.lastrowid
self.conn.commit() self.conn.commit()
# Check the latest message ID for that room # Check the latest message ID for that room
self.cursor.execute("SELECT id from messages WHERE room=? and id != ? ORDER BY id DESC",(room,msgid)) self.cursor.execute("SELECT id from messages WHERE room=? and id != ? ORDER BY id DESC",(room,msgid))
r = self.cursor.fetchone() r = self.cursor.fetchone()
if not r: if not r:
last = None last = 0
else: else:
last = r[0] last = r[0]
return { return {
"status" : "ok", "status" : "ok",
"msgid" : msgid, "msgid" : msgid,
"last" : last "last" : last
} }
  def fetchMsgs(self,reqjson):
  ''' Check to see if there are any new messages in the room
   
  curl -v -X POST http://127.0.0.1:8090/ -H "Content-Type: application/json" --data '{"action":"pollMsg","payload":"{\"roomName\":\"BenTest\", \"mylast\":1,\"user\":\"ben2\"}"}'
   
  '''
   
  if not self.validateUser(reqjson['payload']):
  return 403
   
  if "mylast" not in reqjson['payload']:
  return 400
   
  room = self.getRoomID(reqjson['payload']["roomName"])
  print room
  if not room:
  return 400
   
  self.cursor.execute("""SELECT id,msg FROM messages
  WHERE room=? AND
  id > ?
  ORDER BY ts ASC
  """,(room,reqjson['payload']['mylast']))
   
  r = self.cursor.fetchall()
   
  if not r:
  # No changes
  return {"status":"unchanged","last":reqjson['payload']['mylast']}
   
  # Otherwise, return the messages
  return {"status":"updated",
  "messages" : r
  }
   
   
   
   
   
def validateUser(self,payload): def validateUser(self,payload):
''' Placeholder for now. Auth will be handled later ''' Placeholder for now. Auth will be handled later
''' '''
if "user" not in payload: if "user" not in payload:
return False return False
return True return True
def getRoomID(self,roomname): def getRoomID(self,roomname):
''' Get a room's ID from its name ''' Get a room's ID from its name
''' '''
t = (roomname,) t = (roomname,)
self.cursor.execute("SELECT id from rooms where name=?",t) self.cursor.execute("SELECT id from rooms where name=?",t)
r = self.cursor.fetchone() r = self.cursor.fetchone()
if not r: if not r:
return False return False
return r[0] return r[0]
   
   
def test(self): def test(self):
return ['foo'] return ['foo']
   
   
   
   
# Create a global instance of the wrapper so that state can be retained # Create a global instance of the wrapper so that state can be retained
msghandler = MsgHandler() msghandler = MsgHandler()
   
   
if __name__ == '__main__': if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 8090. # Bind to PORT if defined, otherwise default to 8090.
port = int(os.environ.get('PORT', 8090)) port = int(os.environ.get('PORT', 8090))
app.run(host='0.0.0.0', port=port,debug=True) app.run(host='0.0.0.0', port=port,debug=True)