forked from SpiderBall/irc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
437 lines (341 loc) · 13.4 KB
/
server.py
File metadata and controls
437 lines (341 loc) · 13.4 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import psycopg2
import psycopg2.extras
import traceback
import os
import uuid
from flask import Flask, session, jsonify, request
from flask.ext.socketio import SocketIO, emit, join_room, leave_room
app = Flask(__name__, static_url_path='')
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
def connectToDB():
#print 'in connectToDB'
connectionString = 'dbname=irc_db user=postgres password=pg host=localhost'
try:
return psycopg2.connect(connectionString)
except:
print("Can't connect to database - in server.py")
traceback.print_exc()
messages = [{'text':'test', 'name':'testName'}]
#the list of rooms
rooms = []
#USERS IS A DICTIONARY
users = {}
names = []
#What the actual is this thing doing.
app.debug = True
socketio = SocketIO(app)
messages = [{'text':'test', 'name':'testName'}]
rooms = ['General']
def updateRoster():
names = []
for user_id in users:
if len(users[user_id]['username'])==0:
names.append('Anonymous')
else:
names.append(users[user_id]['username'])
print 'broadcasting names'
traceback.print_exc()
emit('roster', names, broadcast=True)
#UPDATE ROOMS
def updateRooms():
conn = connectToDB()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
room = session['room']
roomInsertQuery="INSERT INTO rooms (id, roomname) VALUES (DEFAULT, %s)"
#this pos isn't working, it either gives me a syntax error
#roomInsertQuery="INSERT INTO rooms (id, roomname) SELECT * FROM rooms WHERE NOT EXISTS (SELECT roomname FROM rooms WHERE roomname = %s)"
try:
cur.execute(roomInsertQuery, (room,))
print "did the thing successfully I guess. after try and before emit"
except:
print "I couldn't do the room insert augh"
traceback.print_exc()
conn.commit()
emit('rooms', rooms)
def getRoomId(roomname):
conn = connectToDB()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
roomIdSelectQuery = "SELECT room_id FROM rooms WHERE roomname = %s;"
id = 0
try:
print "trying to execute select room id"
cur.execute(roomIdSelectQuery, (roomname,))
print "sucessfully executed select room id "
try:
print "trying to grab id"
id = cur.fetchone()
print "this is the current room id" + id
except:
print "could not grab room id"
except:
print "could not execute select room id"
traceback.print_exc()
return id
#we also need a thing that pulls up messages from a chat
#maybe have a subscribe function that determines whether or not join is called??
#THIS IS NOT MINE COPIED FROM DOCUMENTATION, then edited a little bit
#@socketio.on('join', namespace='/chat')
##data needs to become session stuff maybe???
#def on_join(data):
# print "data username is " + data['username']
# print "data room is " + data['room']
# username = data['username']
# room = data['room']
# join_room(room)
# send(username + ' has entered the room.', room=room)
#
#@socketio.on('leave', namespace='/chat')
#def on_leave(data):
# username = data['username']
# room = data['room']
# leave_room(room)
# send(username + ' has left the room.', room=room)
##END COPIED FROM DOCS
#CONNECT
@socketio.on('connect', namespace='/chat') #handles the connect event
def test_connect():
print 'IN CONNECT'
conn = connectToDB()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
session['uuid']=uuid.uuid1()# each time a uuid is called, a new number is returned
session['username']='starter name'
session['room'] = 'General'
#session['room']['room_id'] =
#print 'connected'
#this means that it goes to the users list thing and gets the session id
#this instance of the chat and makes the username field = new user
users[session['uuid']]={'username':'New User'}
updateRoster()
updateRooms()
for item in messages:
emit('message', item)
#MESSAGE
#THIS IS ON LINE 55 IN INDEX.HTML $scope.send - emits message and text
@socketio.on('message', namespace='/chat')
def new_message(message, roomName):
print 'IN MESSAGE'
conn = connectToDB()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
#print 'the message typed was:' + message
updateRooms()
print "just called update rooms, now back in message"
messageToGoInDB = message
print 'the message typed was:' + message
print 'the room typed was:' + roomName
#roomNameQuery = "INSERT into"
room_id = getRoomId(roomName)
print "this is the room id " + str(room_id)
#get id here from users
posterIdQuery = "SELECT id FROM users;"
try:
cur.execute(posterIdQuery)
except:
print("couldn't get posterID from users!")
listOfPosterIDs = cur.fetchall()
originalPosterID = -7
#first get the username of the person who is posting.
thisSessionNum = session['uuid']
currentUsername = users[thisSessionNum]['username']
#then go through database and get that user's id
userIdSelectQuery = "SELECT id FROM users WHERE username = %s"
try:
cur.execute(userIdSelectQuery, (currentUsername,))
except:
print("I had a problem getting the users id from their username.")
usersIdResult = cur.fetchone()
originalPosterID = usersIdResult[0]
#get roomid here
#first get room name from site?
#then do a select for the room id that matches that room name
#but we aren't inserting into the room table yet so we can't do that.
#insert message into the database
insertStatement = "INSERT INTO messages (original_poster_id, message_content, room_id) VALUES (%s, %s, %s)"
try:
cur.execute(insertStatement, (originalPosterID, messageToGoInDB, room_id));
except:
print "there was an error with the insert"
traceback.print_exc()
conn.commit()
#take what is in the database, take from the users column and then
#make it into a python dict called users
tmp = {'text':message, 'username':session['username']}
thisSessionNum = session['uuid']
user = users[thisSessionNum]['username']
if user in users:
tmp = {'text':message, 'username':user}
#messages needs the room stuff too!
#added rooms into tmp, which means that it is a part of the message thing
#from zacharskis
tmp = {'text':message, 'room':roomName, 'username':users[session['uuid']]['username']}
#messages is a list of python dictionaries that look like {messages,users}
messages.append(tmp)
emit('message', tmp, broadcast=True)
#IDENTIFY
#LINE 76ish in index.html? $scope.setName - emits identify scope.name
# $scope.setName2 also emits identify, $scope.name2
@socketio.on('identify', namespace='/chat')
def on_identify(userTypedLoginInfo):
print 'IN IDENTIFY'
# conn = connectToDB()
# cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
#print 'identify' + userTypedLoginInfo
#the message here is where we need to connect to check against the database??
#userTypedLogininfo is the real time variable that is displaying in the server console window and it is being displayed as
#the user types things into the username box.
#we might need to get the username from here and the password from here and get the thing
if 'uuid' in session:
users[session['uuid']]={'username':userTypedLoginInfo}
updateRoster()
else:
print 'sending information'
session['uuid']=uuid.uuid1()
session['username']='starter name'
updateRoster()
updateRooms()
for message in messages:
emit('message', message)
users[session['uuid']]={'username':userTypedLoginInfo}
updateRoster()
updateRooms()
#call update rooms with update roster?
#LOGIN
#around line 85 index.html $scope.processLogin - emits login, $scope.password
@socketio.on('login', namespace='/chat')
def on_login(loginInfo):
print 'IN LOGIN'
conn = connectToDB()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
usernameVar = loginInfo['username']
passwordVar = loginInfo['password']
#print 'user:' + loginInfo['username']
#print 'pass:' + loginInfo['password']
oldMessages = [{'text':'oldMessageInitText', 'username':'oldMessageInitUsername'}]
user_select_string = "SELECT username FROM users WHERE username = %s AND password = %s;"
try:
cur.execute(user_select_string,(usernameVar, passwordVar));
#print 'executed query'
currentUser = cur.fetchone()
if(currentUser is None):
print 'this is not a valid login, please try again'
else:
session['username'] = currentUser['username']
print 'Logged on as:' + session['username']
except:
print 'could not execute login query!'
traceback.print_exc()
#printing all previous messages from database here.
#this part grabs the stuff from messages
messageQuery = "SELECT message_content, original_poster_id FROM messages;"
try:
cur.execute(messageQuery)
except:
print("I couldn't grab messages from the previous database")
previousMessages = cur.fetchall()
for message in previousMessages:
messageStr = str(message['message_content'])
#print 'a previous message was:' + messageStr
idStr = str(message['original_poster_id'])
#print 'the users id was: ' + idStr
#this part grabs the stuff from users
userQuery = "SELECT id, username FROM users WHERE id = %s;"
try:
cur.execute(userQuery, (idStr,))
except:
print("I couldn't grab users from database")
idMatchUserResults = cur.fetchall()
theUserMatchName = ""
for user in idMatchUserResults:
#print 'the id is:' + idStr
theUserMatchName = user['username']
#print 'the username that hopefully matches is' + theUserMatchName
temp = {'text':messageStr, 'username':theUserMatchName}
oldMessages.append(temp)
#oldMessages = [{'text':messageStr, 'username':theUserMatchName}]
count = 0
for item in oldMessages:
if count >= len(oldMessages):
thing = 'nope'
else :
usernameName = oldMessages[count]['username']
messageFromUsername = oldMessages[count]['text']
print messageFromUsername
print 'from:' + usernameName
count = count + 1
#put emit here
emit('message', item)
#what why is this commented out. zacharski did that and I don't know.
#users[session['uuid']]={'username':message}
#updateRoster()
#SEARCH RESULTS
@socketio.on('search', namespace='/chat')
def on_search(searchTerm):
print 'IN SEARCH'
conn = connectToDB()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
#grab search term from database.
#somehow we need to get access to the current room
roomName = session['room']
print roomName
print searchTerm
searchTerm = '%'+ searchTerm +'%'
#make select statement and execute query
searchQuery = "SELECT messages.message_content FROM messages WHERE messages.message_content LIKE %s AND rooms.roomname = %s INNER JOIN messages ON rooms.id = messages.room_id"
try:
print 'entering try'
cur.execute(searchQuery,(roomName, searchTerm));
print 'query successfully executed'
except:
print 'could not execute search query!'
traceback.print_exc()
searchResults = cur.fetchall()
#return and print results in chat messages
for item in searchResults:
print len(searchResults)
if item:
item = {'text': str(item[0])}
emit('search', item)
else:
print 'there is nothing here'
#if time, then print out messages in another spot
#do this by changing emit to send it somewhere else
#need another route here for rooms
#call update rooms
#DISCONNECT
@socketio.on('disconnect', namespace='/chat')
def on_disconnect():
print 'DISCONNECT'
#disconnect happens when you close the thing!
if session['uuid'] in users:
del users[session['uuid']]
updateRoster()
emit('roster', names)
@socketio.on('new_room', namespace='/chat')
def new_room(the_room):
print 'updating rooms'
rooms.append(the_room)
session['room'] = the_room
print the_room
updateRooms()
print 'back'
# return jsonify(success= "ok")
@app.route('/')
def hello_world():
print 'in hello world'
return app.send_static_file('index.html')
return 'Hello World!'
@app.route('/js/<path:path>')
def static_proxy_js(path):
# send_static_file will guess the correct MIME type
return app.send_static_file(os.path.join('js', path))
@app.route('/css/<path:path>')
def static_proxy_css(path):
# send_static_file will guess the correct MIME type
return app.send_static_file(os.path.join('css', path))
@app.route('/img/<path:path>')
def static_proxy_img(path):
# send_static_file will guess the correct MIME type
return app.send_static_file(os.path.join('img', path))
if __name__ == '__main__':
print "A"
socketio.run(app, host=os.getenv('IP', '0.0.0.0'), port=int(os.getenv('PORT', 8080)))