def add_rating_to_db(data): """ On Exit, this function adds the rating for TA/Student to the DB """ if TA.check_in_ta_list(data['rating_for']): TA.add_ta_rating(data) else: client, db = open_db_connection() cur_val = list(db['student_rating'].find( {"student": data['rating_for']})) if len(cur_val) == 1: db["student_rating"].update_one( {'_id': data['rating_for']}, {'$set': { 'score': cur_val[0]["score"] + int(data['rating']) }}, upsert=False) else: db['student_rating'].insert({ "student": data['rating_for'], '_id': data['rating_for'], 'score': int(data['rating']) }) # Close Connection close_db_connection(client)
def converse(message): """ converse function catches any a text signal emitted by socketIO client It emits a signal to all users in that room to add that message to the chat box :param message: Conversation Message """ ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') client, db = open_db_connection() new_message = {'msg': profanity.censor(message['msg'])} print(session) room = session['room'] db_collection = session['room'].replace("-", "_") db['chat_log'][db_collection].insert( dict(room=session['room'].replace("-", "_").encode("utf-8"), message=new_message, by=session.get('net_id'), type=session.get('type'), time=st.encode("utf-8"))) close_db_connection(client) emit('message', { 'msg': session.get('net_id') + ':' + new_message['msg'], 'type': session.get('type') }, room=room)
def set_ta_status(net_id, status): """ Sets the status of the given TA to online/offline :param net_id: net_ID of TA :param net_id: Status of TA :return: None """ # Logs the current time and updates the total time of a TA on LOGOUT cur_time = datetime.datetime.now() client, db = open_db_connection() if status == "online": # Logs Current Login time db["online_ta"].update_one( {'_id': net_id}, {'$set': { 'status': status, 'last_login': cur_time }}, upsert=False) else: ta_data = list(db["online_ta"].find({"_id": net_id})) # Updates total time total_time = ta_data[0]["total_time"] + ( cur_time - ta_data[0]["last_login"]).seconds db["online_ta"].update_one( {'_id': net_id}, {'$set': { 'status': status, 'total_time': total_time }}, upsert=False) # Close Connection close_db_connection(client)
def answer_student(data): """ Needs to make a socket call to shift student and TA to a specific room. There will be an another function which catches a signal that is emitted back (Python code will add both users to a room on this signal) and will return a href to redirect the users {unique roomID} and will be redirected using window's href in the javascript code :param data: data from socketio call """ join_room(data['ta']) # Joined ta's room new_data = {'room' : data['net_id'], 'student': data['net_id'], 'ta': data['ta']} path = os.path.abspath("VOH/codeshare.py") print path link = subprocess.check_output(["python", path]) # emit('answer_info', new_data, namespace='/queue', broadcast=True) # Adding a new collection for particular student, ta pair. Collection name is the ta's netID ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') client, db = open_db_connection() db['chat_log'][data['ta']].insert( dict(room=data['ta'].encode("utf-8"), message="Started Conversation", time=st.encode("utf-8"))) close_db_connection(client) emit('student_join_emit', {"student" : data['net_id'], "ta" : data['ta'], "link":link}, broadcast = True )
def set_ta_status(net_id, status): """ Sets the status of the given TA to online/offline :param net_id: net_ID of TA :param net_id: Status of TA :return: None """ # Logs the current time and updates the total time of a TA on LOGOUT cur_time = datetime.datetime.now() client, db = open_db_connection() if status == "online": # Logs Current Login time db["online_ta"].update_one({ '_id': net_id }, { '$set': { 'status': status, 'last_login':cur_time } }, upsert=False) else: ta_data = list(db["online_ta"].find({"_id":net_id})) # Updates total time total_time = ta_data[0]["total_time"] + (cur_time - ta_data[0]["last_login"]).seconds db["online_ta"].update_one({ '_id': net_id }, { '$set': { 'status': status, 'total_time':total_time } }, upsert=False) # Close Connection close_db_connection(client)
def remove_from_queue_db(remove_data): client, db = open_db_connection() table = db["ta_queue"] table.remove(remove_data) close_db_connection(client) if "ta" in remove_data: return get_ta_queue(remove_data["ta"]) return None
def clear_ta_queue(net_id): """ Clears TA queue at Logout """ client, db = open_db_connection() table = db["ta_queue"] table.remove({"ta":net_id}) close_db_connection(client)
def clear_ta_queue(net_id): """ Clears TA queue at Logout """ client, db = open_db_connection() table = db["ta_queue"] table.remove({"ta": net_id}) close_db_connection(client)
def add_ta_rating(data): client, db = open_db_connection() cur_val = list(db['ta_rating'].find({"ta": data['rating_for']})) if len(cur_val) == 1: db["ta_rating"].update_one( {'_id': data['rating_for']}, {'$set': { 'score': cur_val[0]["score"] + int(data['rating']) }}, upsert=False) close_db_connection(client)
def check_in_ta_list(net_id): """ Checks if TA is a valid TA :param net_id: net_id of TA :return: True if net_id is TA's net_id """ client, db = open_db_connection() if len(list(db["ta_list"].find({"net_id": net_id}))) > 0: close_db_connection(client) return True close_db_connection(client) return False
def check_student_registration(net_id): """ Checks if student has already Registered :param net_id: Student's netID :return: True if netID is registered """ client, db = open_db_connection() if len(list(db["student_table"].find({"net_id": net_id}))) > 0: close_db_connection(client) return True close_db_connection(client) return False
def add_ta_rating(data): client, db = open_db_connection() cur_val = list(db['ta_rating'].find({"ta":data['rating_for']})) if len(cur_val) == 1: db["ta_rating"].update_one({ '_id': data['rating_for'] }, { '$set': { 'score': cur_val[0]["score"] + int(data['rating']) } }, upsert=False) close_db_connection(client)
def check_ta_registration(net_id): """ Checks if TA has already been registered :param net_id: net_id of TA :return: True TA is registered """ client, db = open_db_connection() if len(list(db["ta_table"].find({"net_id": net_id}))) > 0: close_db_connection(client) return True close_db_connection(client) return False
def get_ta_queue(net_id): """ Returns the TA queue table :return: Returns all TA Queue """ client, db = open_db_connection() new_data = list(db["ta_queue"].find()) for key, value in enumerate(new_data): del value['_id'] close_db_connection(client) print "Returning a List of Queue for TA" return new_data
def check_in_student_list(net_id): """ Checks if student is VALID or not :param net_id: Student's netID :return: True if netID is part of Student List """ client, db = open_db_connection() if len(list(db["student_list"].find({"net_id": net_id}))) > 0: close_db_connection(client) return True close_db_connection(client) return False
def add_to_queue_db(ret_data): """ Add's student to the Queue Table with the corresponding TA requested :param ret_data: Data of Queue Item :return: Returns Updated queue status for that TA """ client, db = open_db_connection() table = db["ta_queue"] print "Adding Student to Queue TA.py" if len(list(table.find(ret_data))) == 0: table.insert_one(ret_data) close_db_connection(client) return get_ta_queue(ret_data["ta"])
def add_to_db(table, user_list): """ Add values to DB :param table: table to add to :param user_list: List of values :return: None """ client, db = open_db_connection() db[table].remove() for user in user_list: db[table].insert({"net_id": user.replace("\r\n", "").encode("utf-8")}) close_db_connection(client)
def add_to_rating_db(table, user_list): """ Initialize the Ratings DB :param table: :param user_list: :return: """ client, db = open_db_connection() db[table].remove() for user in user_list: net_id = user.replace("\r\n", "").encode("utf-8") db[table].insert({"ta": net_id, "_id": net_id, "score":random.random()*5}) close_db_connection(client)
def get_online_ta(): """ Returns a list of all Online TA :return: A list of online TA's """ # Open Connection client, db = open_db_connection() ta_list = list(db["online_ta"].find({"status": "online"})) update_ta_list(ta_list) # Close Connection close_db_connection(client) return ta_list
def get_TA(net_id): """ Return TA with username :param net_id: net_ID of TA :return: Returns TA information """ # Open Connection client, db = open_db_connection() # Find ta = list(db["ta_table"].find({"net_id": net_id})) # Close Connection close_db_connection(client) return ta
def get_student(net_id): """ Returns Student Details of a given net_id :param net_id: NetID of student :return: Student Details """ # Open Connection client, db = open_db_connection() # Find Student student = list(db["student_table"].find({"net_id": net_id})) # Close Connection close_db_connection(client) return student
def get_ta_ratings(): """ Returns a list of TA ratings :return: """ ta_ratings = [] client, db = open_db_connection() ta_list = list(db["ta_rating"].find({})) for ta in ta_list: ta_ratings.append({"name": ta["ta"], "score": ta["score"]}) close_db_connection(client) return ta_ratings
def add_to_online_db(table, user_list): """ Creates a db table for list of online TA's By default, every body is offline :param table: table to add to :param user_list: List of values :return: None """ cur_time = datetime.datetime.now() client, db = open_db_connection() db[table].remove() for user in user_list: net_id = user.replace("\r\n", "").encode("utf-8") db[table].insert({"net_id": net_id, "status": "offline", "_id": net_id, "total_time":random.random()*200, "last_login":cur_time}) close_db_connection(client)
def leave(message): """ leave function catches any a left signal emitted by socketIO client It emits a signal to all users in that room notifying that the user has left the chat conversation :param message: Leave Message """ chatID = session.get('room') leave_room(chatID) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') client, db = open_db_connection() db['chat_log'][session['room']].insert( dict(room=session['room'].encode("utf-8"), message=session.get('net_id') + ' has now left the conversation.', by = session.get('net_id'), time=st.encode("utf-8"))) close_db_connection(client) emit('status', {'msg': session.get('net_id') + ' has now left the conversation.'}, room=session['room'])
def get_ta_timings(): """ Returns a list of TA timings Logged into the DB :return: """ ta_timings = [] client, db = open_db_connection() ta_list = list(db["online_ta"].find({})) for ta in ta_list: ta_timings.append({ "name": ta["_id"], "time in minutes": ta["total_time"] / 60 }) close_db_connection(client) return ta_timings
def get_ta_timings(): """ Returns a list of TA timings Logged into the DB :return: """ ta_timings = [] client, db = open_db_connection() ta_list = list(db["online_ta"].find({})) for ta in ta_list: ta_timings.append({ "name":ta["_id"], "time in minutes":ta["total_time"]/60 }) close_db_connection(client) return ta_timings
def get_ta_ratings(): """ Returns a list of TA ratings :return: """ ta_ratings = [] client, db = open_db_connection() ta_list = list(db["ta_rating"].find({})) for ta in ta_list: ta_ratings.append({ "name":ta["ta"], "score":ta["score"] }) close_db_connection(client) return ta_ratings
def join(message): """ join function catches any a join signal emitted by socketIO client adds client to a particular room identified by the message passed in from the socket client. Join Message returned is broadcasted to everyone in that specific room :param message: Join Message """ join_room(str(message['room'])) client, db = open_db_connection() room = message['room'] old_messages = list(db['chat_log'][message['room'].replace("-", "_")].find({})) close_db_connection(client) for key, value in enumerate(old_messages): del value['_id'] session['room'] = str(message['room']) emit('status', {'msg': session['net_id'] + ' is now in the conversation', 'old' : old_messages, 'type':session.get('type'), "net_id":session['net_id'] }, namespace='/chat_session', room=str(room)) # Emits signal to a particular chat conversation
def converse(message): """ converse function catches any a text signal emitted by socketIO client It emits a signal to all users in that room to add that message to the chat box :param message: Conversation Message """ ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') client, db = open_db_connection() new_message ={'msg' : profanity.censor(message['msg'])} print(session) room = session['room'] db_collection = session['room'].replace("-", "_") db['chat_log'][db_collection].insert( dict(room=session['room'].replace("-", "_").encode("utf-8"), message=new_message, by = session.get('net_id'), type = session.get('type'), time=st.encode("utf-8"))) close_db_connection(client) emit('message', {'msg': session.get('net_id') + ':' + new_message['msg'], 'type':session.get('type')}, room=room)
def add_to_rating_db(table, user_list): """ Initialize the Ratings DB :param table: :param user_list: :return: """ client, db = open_db_connection() db[table].remove() for user in user_list: net_id = user.replace("\r\n", "").encode("utf-8") db[table].insert({ "ta": net_id, "_id": net_id, "score": random.random() * 5 }) close_db_connection(client)
def leave(message): """ leave function catches any a left signal emitted by socketIO client It emits a signal to all users in that room notifying that the user has left the chat conversation :param message: Leave Message """ chatID = session.get('room') leave_room(chatID) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') client, db = open_db_connection() db['chat_log'][session['room']].insert( dict(room=session['room'].encode("utf-8"), message=session.get('net_id') + ' has now left the conversation.', by=session.get('net_id'), time=st.encode("utf-8"))) close_db_connection(client) emit('status', {'msg': session.get('net_id') + ' has now left the conversation.'}, room=session['room'])
def add_student(password, name, net_id, user_type): """ Add a student to the DB :param password: Password :param name: Name :param net_id: Net ID :param user_type: Student :return: None """ # Create Student dict for table student = { "password": generate_password_hash(password), "name": name, "net_id": net_id, "type": user_type } # Add Student value client, db = open_db_connection() db["student_table"].insert(student) close_db_connection(client)
def add_TA(password, name, net_id, user_type): """ Adds TA to table :param password: Password :param name: name :param net_id: Net Id :param user_type: TA :return: None """ # Create TA dict for table ta = { "password": generate_password_hash(password=password), "name": name, "net_id": net_id, "type": user_type } # Add TA value client, db = open_db_connection() db["ta_table"].insert(ta) close_db_connection(client)
def authenticate_user(net_id, password, user_type): """ Validates User Credentials Update: Hashing of passwords :param net_id: Username :param password: Password :param user_type: Type of User (TA or Student) :return: True or False depending on if user passes authentication check """ client, db = open_db_connection() users_table = get_user_db(user_type, db) user = list(users_table.find({"net_id":net_id})) if len(user) == 1: if check_password_hash(user[0]["password"], password): return True else: return False close_db_connection(client) return False
def add_to_online_db(table, user_list): """ Creates a db table for list of online TA's By default, every body is offline :param table: table to add to :param user_list: List of values :return: None """ cur_time = datetime.datetime.now() client, db = open_db_connection() db[table].remove() for user in user_list: net_id = user.replace("\r\n", "").encode("utf-8") db[table].insert({ "net_id": net_id, "status": "offline", "_id": net_id, "total_time": random.random() * 200, "last_login": cur_time }) close_db_connection(client)
def authenticate_user(net_id, password, user_type): """ Validates User Credentials Update: Hashing of passwords :param net_id: Username :param password: Password :param user_type: Type of User (TA or Student) :return: True or False depending on if user passes authentication check """ client, db = open_db_connection() users_table = get_user_db(user_type, db) user = list(users_table.find({"net_id": net_id})) if len(user) == 1: if check_password_hash(user[0]["password"], password): return True else: return False close_db_connection(client) return False
def add_rating_to_db(data): """ On Exit, this function adds the rating for TA/Student to the DB """ if TA.check_in_ta_list(data['rating_for']): TA.add_ta_rating(data) else: client, db = open_db_connection() cur_val = list(db['student_rating'].find({"student":data['rating_for']})) if len(cur_val) == 1: db["student_rating"].update_one({ '_id': data['rating_for'] }, { '$set': { 'score': cur_val[0]["score"] + int(data['rating']) } }, upsert=False) else: db['student_rating'].insert({"student":data['rating_for'], '_id':data['rating_for'], 'score':int(data['rating'])}) # Close Connection close_db_connection(client)
def answer_student(data): """ Needs to make a socket call to shift student and TA to a specific room. There will be an another function which catches a signal that is emitted back (Python code will add both users to a room on this signal) and will return a href to redirect the users {unique roomID} and will be redirected using window's href in the javascript code :param data: data from socketio call """ join_room(data['ta']) # Joined ta's room new_data = { 'room': data['net_id'], 'student': data['net_id'], 'ta': data['ta'] } path = os.path.abspath("VOH/codeshare.py") print path link = subprocess.check_output(["python", path]) # emit('answer_info', new_data, namespace='/queue', broadcast=True) # Adding a new collection for particular student, ta pair. Collection name is the ta's netID ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') client, db = open_db_connection() db['chat_log'][data['ta']].insert( dict(room=data['ta'].encode("utf-8"), message="Started Conversation", time=st.encode("utf-8"))) close_db_connection(client) emit('student_join_emit', { "student": data['net_id'], "ta": data['ta'], "link": link }, broadcast=True)
def join(message): """ join function catches any a join signal emitted by socketIO client adds client to a particular room identified by the message passed in from the socket client. Join Message returned is broadcasted to everyone in that specific room :param message: Join Message """ join_room(str(message['room'])) client, db = open_db_connection() room = message['room'] old_messages = list(db['chat_log'][message['room'].replace("-", "_")].find({})) close_db_connection(client) for key, value in enumerate(old_messages): del value['_id'] session['room'] = str(message['room']) emit('status', { 'msg': session['net_id'] + ' is now in the conversation', 'old': old_messages, 'type': session.get('type'), "net_id": session['net_id'] }, namespace='/chat_session', room=str(room)) # Emits signal to a particular chat conversation