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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
| #!/usr/bin/env python
#
#
# LocalChat Server Script
#
#
# apt-get install:
# python-flask
#
from flask import Flask
from flask import request, make_response
import sqlite3
import time
import os
import json
app = Flask(__name__)
@app.route('/', defaults={'path': ''},methods=["POST"])
@app.route('/<path:path>',methods=["POST"])
def index(path):
print "%.6f Request start" % (time.time()) # DEBUGONLY
reqdata = request.get_data()
try:
reqjson = json.loads(reqdata)
except:
return make_response("",400)
a = msghandler.processSubmission(reqjson)
# Check the status
if a in [400,403]:
response = make_response("",a)
return response
return json.dumps(a)
class MsgHandler(object):
def __init__(self):
self.conn = False
self.cursor = False
def createDB(self):
''' Create the in-memory database ready for use
'''
self.conn = sqlite3.connect(':memory:')
self.cursor = self.conn.cursor()
sql = """ CREATE TABLE rooms (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
owner TEXT NOT NULL,
pass TEXT NOT NULL
);
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
ts INTEGER NOT NULL,
room INTEGER NOT NULL,
msg TEXT NOT NULL
);
CREATE TABLE users (
username TEXT NOT NULL,
room INTEGER NOT NULL,
PRIMARY KEY (username,room)
);
"""
self.conn.executescript(sql)
def processSubmission(self,reqjson):
''' Process an incoming request and route it to
the correct function
'''
if not self.conn or not self.cursor:
self.createDB()
print reqjson
if "action" not in reqjson or "payload" not in reqjson:
return 400
# Decrypt the payload
reqjson['payload'] = self.decrypt(reqjson['payload'])
try:
reqjson['payload'] = json.loads(reqjson['payload'])
except:
return 400
if reqjson['action'] == "createRoom":
return self.createRoom(reqjson)
elif reqjson['action'] == "inviteUser":
return self.inviteUser(reqjson)
elif reqjson['action'] == 'sendMsg':
return self.sendMsg(reqjson)
elif reqjson['action'] == 'pollMsg':
return self.fetchMsgs(reqjson)
def decrypt(self,msg):
''' This is currently just a placeholder
Will be updated later
'''
return msg
def createRoom(self,reqjson):
'''
Payload should contain a JSON object consisting of
roomName
owner
passhash
e.g.
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\"
}"
}'
'''
print "Creating room %s" % (reqjson['payload'])
# Create a tuple for sqlite3
t = (reqjson['payload']['roomName'],
reqjson['payload']['owner'],
reqjson['payload']['passhash'])
try:
self.cursor.execute("INSERT INTO rooms (name,owner,pass) VALUES (?,?,?)",t)
roomid = self.cursor.lastrowid
except:
# Probably a duplicate name, but we don't want to give the other end a reason anyway
return 500
self.cursor.execute("INSERT INTO users (username,room) values (?,?)",(reqjson['payload']['owner'],roomid))
self.conn.commit()
return {
'status':'ok',
'roomid': roomid,
'name' : reqjson['payload']['roomName']
}
def inviteUser(self,reqjson):
''' 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\"}"}'
'''
if "roomName" not in reqjson['payload']:
return 400
room = self.getRoomID(reqjson['payload']["roomName"])
if not room:
return 400
# Otherwise, link the user in
self.cursor.execute("INSERT INTO users (username,room) values (?,?)",(reqjson['payload']['user'],room))
self.conn.commit()
return {
"status":'ok'
}
def sendMsg(self,reqjson):
''' 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\"}"}'
'''
if not self.validateUser(reqjson['payload']):
return 403
if "roomName" not in reqjson['payload'] or "msg" not in reqjson['payload']:
return 400
room = self.getRoomID(reqjson['payload']["roomName"])
print room
if not room:
return 400
self.cursor.execute("INSERT INTO messages (ts,room,msg) VALUES (?,?,?)",(time.time(),room,reqjson['payload']['msg']))
msgid = self.cursor.lastrowid
self.conn.commit()
# 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))
r = self.cursor.fetchone()
if not r:
last = 0
else:
last = r[0]
return {
"status" : "ok",
"msgid" : msgid,
"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):
''' Placeholder for now. Auth will be handled later
'''
if "user" not in payload:
return False
return True
def getRoomID(self,roomname):
''' Get a room's ID from its name
'''
t = (roomname,)
self.cursor.execute("SELECT id from rooms where name=?",t)
r = self.cursor.fetchone()
if not r:
return False
return r[0]
def test(self):
return ['foo']
# Create a global instance of the wrapper so that state can be retained
msghandler = MsgHandler()
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 8090.
port = int(os.environ.get('PORT', 8090))
app.run(host='0.0.0.0', port=port,debug=True)
|