async def requestReceived(websocket, session, request): global studentClassesSubscribers if websocket.authenticated == False: await websocket.send(convertToJson({'operation' : 'tokenError', 'table' : 'TokenAuthentication'})) return #Websockets endpoints if request['operation'] == 'get': #get endpoint studentClasses = StudentClasse.getStudentClasses(session) response = convertToJson({'operation' : 'get', 'table' : 'StudentClasses', 'data' : studentClasses}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint studentClasses = StudentClasse.getStudentClasses(session) response = convertToJson({'operation' : 'get', 'table' : 'StudentClasses', 'data' : studentClasses}) studentClassesSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['studentId', 'classeId']) == False: print('Not all parameters were provided for ADD in StudentClasses') await websocket.send(convertToJson({'error' : 'Invalid request'})) return studentClasse = dict_as_obj(request['data'], StudentClasse.StudentClasse(), ['studentClasseId', 'creationTime']) studentClasse = StudentClasse.addStudentClasse(session, studentClasse) response = convertToJson({'operation' : 'add', 'table' : 'StudentClasses', 'data' : studentClasse}) studentClassesSubscribers = set(filter(removeClosedConnection, studentClassesSubscribers)) for subscriber in studentClassesSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['studentClasseId']) == False: print('Not all parameters were provided for UPDATE in StudentClasses') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] studentClasse = StudentClasse.getStudentClassesByStudentClasseId(session, data['studentClasseId'])[0] studentClasse = dict_as_obj(data, studentClasse) studentClasse = StudentClasse.updateStudentClasse(session, studentClasse) response = convertToJson({'operation' : 'update', 'table' : 'StudentClasses', 'data' : studentClasse}) studentClassesSubscribers = set(filter(removeClosedConnection, studentClassesSubscribers)) for subscriber in studentClassesSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['studentClasseId']) == False: print('Not all parameters were provided for DELETE in StudentClasses') await websocket.send(convertToJson({'error' : 'Invalid request'})) return studentClasse = StudentClasse.deleteStudentClasse(session, request['data']['studentClasseId']) response = convertToJson({'operation' : 'delete', 'table' : 'StudentClasses', 'data' : studentClasse}) studentClassesSubscribers = set(filter(removeClosedConnection, studentClassesSubscribers)) for subscriber in studentClassesSubscribers: await subscriber.send(response)
async def requestReceived(websocket, session, request): global marksSubscribers if websocket.authenticated == False: await websocket.send(convertToJson({'operation' : 'tokenError', 'table' : 'TokenAuthentication'})) return #Websockets endpoints if request['operation'] == 'get': #get endpoint marks = Mark.getMarks(session) response = convertToJson({'operation' : 'get', 'table' : 'Marks', 'data' : marks}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint marks = Mark.getMarks(session) response = convertToJson({'operation' : 'get', 'table' : 'Marks', 'data' : marks}) marksSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['classeId', 'studentId', 'teacherId', 'value', 'date']) == False: print('Not all parameters were provided for ADD in Marks') await websocket.send(convertToJson({'error' : 'Invalid request'})) return mark = dict_as_obj(request['data'], Mark.Mark(), ['markId', 'creationTime']) mark = Mark.addMark(session, mark) response = convertToJson({'operation' : 'add', 'table' : 'Marks', 'data' : mark}) marksSubscribers = set(filter(removeClosedConnection, marksSubscribers)) for subscriber in marksSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['markId']) == False: print('Not all parameters were provided for UPDATE in Marks') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] mark = Mark.getMarksByMarkId(session, data['markId'])[0] mark = dict_as_obj(data, mark) mark = Mark.updateMark(session, mark) response = convertToJson({'operation' : 'update', 'table' : 'Marks', 'data' : mark}) marksSubscribers = set(filter(removeClosedConnection, marksSubscribers)) for subscriber in marksSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['markId']) == False: print('Not all parameters were provided for DELETE in Marks') await websocket.send(convertToJson({'error' : 'Invalid request'})) return mark = Mark.deleteMark(session, request['data']['markId']) response = convertToJson({'operation' : 'delete', 'table' : 'Marks', 'data' : mark}) marksSubscribers = set(filter(removeClosedConnection, marksSubscribers)) for subscriber in marksSubscribers: await subscriber.send(response)
async def shuffleCards(session, playersConnected): print(playersConnected) print(len(playersConnected)) cards=[] for i in range(2, 15): for j in range(0, 4): if i==2 and len(playersConnected)==6: break cards.append(Card.Card(type=j, number=i, playerId=0)) if i==2 and j==2 and len(playersConnected)==3: break if i==2 and j==1 and len(playersConnected)==5: break playerIndex = 0 while len(cards) > 0: print(len(cards)) card = cards[floor(random() * len(cards))] card.playerId = playersConnected[playerIndex]['player'].playerId newCard = Card.addCard(session, card) playersConnected[playerIndex]['cards'].append(newCard) playerIndex = (playerIndex + 1) % len(playersConnected) cards.remove(card) cards = Card.getCards(session) response = convertToJson({'operation' : 'get', 'table' : 'Cards', 'data' : cards}) for player in playersConnected: await player['socket'].send(response)
async def changeCards(session, playersConnected, looser, winner, numberCards): winnerCards = Card.getCardsByPlayerIdSorted(session, winner["player"].playerId) looserCards = Card.getCardsByPlayerIdSorted(session, looser["player"].playerId) print("change ", numberCards, "between winner ", winner["player"].name, "and ", looser["player"].name) print(winnerCards) for card in winnerCards: print(card.number) for index in range(0, numberCards): card = winnerCards[index] winner["cards"].remove(card) card.playerId = looser["player"].playerId card = Card.updateCard(session, card) looser["cards"].append(card) for index in range(len(looserCards) - numberCards, len(looserCards)): card = looserCards[index] looser["cards"].remove(card) card.playerId = winner["player"].playerId card = Card.updateCard(session, card) winner["cards"].append(card) #update score winner["score"] = winner["score"] + numberCards looser["score"] = looser["score"] - numberCards cards = Card.getCards(session) response = convertToJson({'operation' : 'get', 'table' : 'Cards', 'data' : cards}) for player in playersConnected: await player['socket'].send(response)
async def requestReceived(websocket, session, request): global notificationsSubscribers #Websockets endpoints if request['operation'] == 'get': #get endpoint notifications = Notification.getNotifications(session) response = convertToJson({'operation' : 'get', 'table' : 'Notifications', 'data' : notifications}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint notifications = Notification.getNotifications(session) response = convertToJson({'operation' : 'get', 'table' : 'Notifications', 'data' : notifications}) notificationsSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['title', 'message']) == False: print('Not all parameters were provided for ADD in Notifications') await websocket.send(convertToJson({'error' : 'Invalid request'})) return notification = dict_as_obj(request['data'], Notification.Notification(), ['notificationId', 'creationTime']) notification = Notification.addNotification(session, notification) response = convertToJson({'operation' : 'add', 'table' : 'Notifications', 'data' : notification}) notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers)) for subscriber in notificationsSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['notificationId']) == False: print('Not all parameters were provided for UPDATE in Notifications') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] notification = Notification.getNotificationsByNotificationId(session, data['notificationId'])[0] notification = dict_as_obj(data, notification) notification = Notification.updateNotification(session, notification) response = convertToJson({'operation' : 'update', 'table' : 'Notifications', 'data' : notification}) notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers)) for subscriber in notificationsSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['notificationId']) == False: print('Not all parameters were provided for DELETE in Notifications') await websocket.send(convertToJson({'error' : 'Invalid request'})) return notification = Notification.deleteNotification(session, request['data']['notificationId']) response = convertToJson({'operation' : 'delete', 'table' : 'Notifications', 'data' : notification}) notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers)) for subscriber in notificationsSubscribers: await subscriber.send(response)
async def requestReceived(websocket, session, request): global tokenUsersSubscribers #Websockets endpoints if request['operation'] == 'get': #get endpoint tokenUsers = TokenUser.getTokenUsers(session) response = convertToJson({'operation' : 'get', 'table' : 'TokenUsers', 'data' : tokenUsers}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint tokenUsers = TokenUser.getTokenUsers(session) response = convertToJson({'operation' : 'get', 'table' : 'TokenUsers', 'data' : tokenUsers}) tokenUsersSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['username', 'password', 'type']) == False: print('Not all parameters were provided for ADD in TokenUsers') await websocket.send(convertToJson({'error' : 'Invalid request'})) return tokenUser = dict_as_obj(request['data'], TokenUser.TokenUser(), ['tokenUserId', 'creationTime']) tokenUser = TokenUser.addTokenUser(session, tokenUser) response = convertToJson({'operation' : 'add', 'table' : 'TokenUsers', 'data' : tokenUser}) tokenUsersSubscribers = set(filter(removeClosedConnection, tokenUsersSubscribers)) for subscriber in tokenUsersSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['tokenUserId']) == False: print('Not all parameters were provided for UPDATE in TokenUsers') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] tokenUser = TokenUser.getTokenUsersByTokenUserId(session, data['tokenUserId'])[0] tokenUser = dict_as_obj(data, tokenUser) tokenUser = TokenUser.updateTokenUser(session, tokenUser) response = convertToJson({'operation' : 'update', 'table' : 'TokenUsers', 'data' : tokenUser}) tokenUsersSubscribers = set(filter(removeClosedConnection, tokenUsersSubscribers)) for subscriber in tokenUsersSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['tokenUserId']) == False: print('Not all parameters were provided for DELETE in TokenUsers') await websocket.send(convertToJson({'error' : 'Invalid request'})) return tokenUser = TokenUser.deleteTokenUser(session, request['data']['tokenUserId']) response = convertToJson({'operation' : 'delete', 'table' : 'TokenUsers', 'data' : tokenUser}) tokenUsersSubscribers = set(filter(removeClosedConnection, tokenUsersSubscribers)) for subscriber in tokenUsersSubscribers: await subscriber.send(response)
async def requestReceived(websocket, session, request): global cardsSubscribers #Websockets endpoints if request['operation'] == 'get': #get endpoint cards = Card.getCards(session) response = convertToJson({'operation' : 'get', 'table' : 'Cards', 'data' : cards}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint cards = Card.getCards(session) response = convertToJson({'operation' : 'get', 'table' : 'Cards', 'data' : cards}) cardsSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['playerId', 'type', 'number']) == False: print('Not all parameters were provided for ADD in Cards') await websocket.send(convertToJson({'error' : 'Invalid request'})) return card = dict_as_obj(request['data'], Card.Card(), ['cardId', 'creationTime']) card = Card.addCard(session, card) response = convertToJson({'operation' : 'add', 'table' : 'Cards', 'data' : card}) cardsSubscribers = set(filter(removeClosedConnection, cardsSubscribers)) for subscriber in cardsSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['cardId']) == False: print('Not all parameters were provided for UPDATE in Cards') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] card = Card.getCardsByCardId(session, data['cardId'])[0] card = dict_as_obj(data, card) card = Card.updateCard(session, card) response = convertToJson({'operation' : 'update', 'table' : 'Cards', 'data' : card}) cardsSubscribers = set(filter(removeClosedConnection, cardsSubscribers)) for subscriber in cardsSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['cardId']) == False: print('Not all parameters were provided for DELETE in Cards') await websocket.send(convertToJson({'error' : 'Invalid request'})) return card = Card.deleteCard(session, request['data']['cardId']) response = convertToJson({'operation' : 'delete', 'table' : 'Cards', 'data' : card}) cardsSubscribers = set(filter(removeClosedConnection, cardsSubscribers)) for subscriber in cardsSubscribers: await subscriber.send(response)
async def sendScoreboard(): global playersConnected score = [] for player in playersConnected: score.append({"name" : player["player"].name, "score" : player["score"]}) sortedScore = sorted(score, key=lambda x: x["score"], reverse=True) scoreMessage = convertToJson({'operation' : 'scoreboard', 'table' : 'Game', 'data' : sortedScore}) for player in playersConnected: await player['socket'].send(scoreMessage)
async def removeCardsFromPlayer(session, playersConnected, player): print("remove cards for player ", player["player"].name) player["cards"] = [] Card.deleteAllCardsForAPlayer(session, player["player"].playerId) cards = Card.getCards(session) response = convertToJson({'operation' : 'get', 'table' : 'Cards', 'data' : cards}) for player in filterOpenedConnectionPlayers(playersConnected): await player['socket'].send(response)
async def requestReceived(websocket, session, request): if request['operation'] == 'login': data = request['data'] if 'username' not in data or 'password' not in data: await websocket.send( convertToJson({ 'table': 'TokenAuthentication', 'operation': 'invalidCredentials' })) return token, isSuccessful = Authentication.login(session, data['username'], data['password'], websocket.remote_address[0]) if isSuccessful == 0: await websocket.send( convertToJson({ 'table': 'TokenAuthentication', 'operation': 'invalidCredentials' })) return await websocket.send( convertToJson({ 'table': 'TokenAuthentication', 'operation': 'authenticationGranted', 'data': token })) websocket.authenticated = True elif request['operation'] == 'setToken': data = request['data'] if 'token' not in data: await websocket.send( convertToJson({ 'table': 'TokenAuthentication', 'operation': 'invalidToken' })) return isAuthorized, error = Authentication.checkToken( session, data['token'], websocket.remote_address[0]) if isAuthorized == 0: await websocket.send( convertToJson({ 'table': 'TokenAuthentication', 'operation': 'invalidToken', 'data': { 'error': error } })) return await websocket.send( convertToJson({ 'table': 'TokenAuthentication', 'operation': 'validToken' })) websocket.authenticated = True
async def cardSelected(session, playersConnected, data): global cardsSubscribers for player in playersConnected: if player['player'].playerId == data["cards"][0]['playerId']: print("player gasit",len(player['cards']), range(0, 15)) for card in data["cards"]: for i in range(0, len(player['cards'])): print(i) cardP = player['cards'][i] if cardP.cardId == card['cardId']: print("carte gasita") player['cards'].remove(cardP) break for card in data["cards"]: card = Card.deleteCard(session, card['cardId']) response = convertToJson({'operation' : 'delete', 'table' : 'Cards', 'data' : card}) cardsSubscribers = set(filter(removeClosedConnection, cardsSubscribers)) for subscriber in cardsSubscribers: await subscriber.send(response)
def output_json(data, code, headers=None): print(data) resp = make_response(convertToJson(data), code) resp.headers.extend(headers or {}) return resp
async def requestReceived(websocket, session, request): global classRoomsSubscribers if websocket.authenticated == False: await websocket.send( convertToJson({ 'operation': 'tokenError', 'table': 'TokenAuthentication' })) return #Websockets endpoints if request['operation'] == 'get': #get endpoint classRooms = ClassRoom.getClassRooms(session) response = convertToJson({ 'operation': 'get', 'table': 'ClassRooms', 'data': classRooms }) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint classRooms = ClassRoom.getClassRooms(session) response = convertToJson({ 'operation': 'get', 'table': 'ClassRooms', 'data': classRooms }) classRoomsSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['name']) == False: print('Not all parameters were provided for ADD in ClassRooms') await websocket.send(convertToJson({'error': 'Invalid request'})) return classRoom = dict_as_obj(request['data'], ClassRoom.ClassRoom(), ['classRoomId', 'creationTime']) classRoom = ClassRoom.addClassRoom(session, classRoom) response = convertToJson({ 'operation': 'add', 'table': 'ClassRooms', 'data': classRoom }) classRoomsSubscribers = set( filter(removeClosedConnection, classRoomsSubscribers)) for subscriber in classRoomsSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['classRoomId']) == False: print('Not all parameters were provided for UPDATE in ClassRooms') await websocket.send(convertToJson({'error': 'Invalid request'})) return data = request['data'] classRoom = ClassRoom.getClassRoomsByClassRoomId( session, data['classRoomId'])[0] classRoom = dict_as_obj(data, classRoom) classRoom = ClassRoom.updateClassRoom(session, classRoom) response = convertToJson({ 'operation': 'update', 'table': 'ClassRooms', 'data': classRoom }) classRoomsSubscribers = set( filter(removeClosedConnection, classRoomsSubscribers)) for subscriber in classRoomsSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['classRoomId']) == False: print('Not all parameters were provided for DELETE in ClassRooms') await websocket.send(convertToJson({'error': 'Invalid request'})) return classRoom = ClassRoom.deleteClassRoom(session, request['data']['classRoomId']) response = convertToJson({ 'operation': 'delete', 'table': 'ClassRooms', 'data': classRoom }) classRoomsSubscribers = set( filter(removeClosedConnection, classRoomsSubscribers)) for subscriber in classRoomsSubscribers: await subscriber.send(response)
async def setTurn(session, playersConnected, turn, lastCard, nrCardsPerTurn): turnMessage = convertToJson({'operation' : 'turn', 'table' : 'Game', 'data' : {'playerIndex' : turn, 'lastCard' : lastCard, "nrCards" : nrCardsPerTurn}}) for player in filterOpenedConnectionPlayers(playersConnected): await player['socket'].send(turnMessage)
async def requestReceived(websocket, session, playersConnected, request): global playersSubscribers #Websockets endpoints if request['operation'] == 'get': #get endpoint players = Player.getPlayers(session) response = convertToJson({'operation' : 'get', 'table' : 'Players', 'data' : players}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint players = Player.getPlayers(session) response = convertToJson({'operation' : 'get', 'table' : 'Players', 'data' : players}) playersSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['name', 'type']) == False: print('Not all parameters were provided for ADD in Players') await websocket.send(convertToJson({'error' : 'Invalid request'})) return player = dict_as_obj(request['data'], Player.Player(), ['playerId', 'creationTime']) player = Player.addPlayer(session, player) playersConnected.append({'player':player, 'socket':websocket, 'cards' : [], 'turnPassed' : False, 'rank' : -1, 'score' : 0}) #inform player response = convertToJson({'operation' : 'registered', 'table' : 'Game', 'data' : player}) await websocket.send(response) response = convertToJson({'operation' : 'add', 'table' : 'Players', 'data' : player}) playersSubscribers = set(filter(removeClosedConnection, playersSubscribers)) for subscriber in playersSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['playerId']) == False: print('Not all parameters were provided for UPDATE in Players') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] player = Player.getPlayersByPlayerId(session, data['playerId'])[0] player = dict_as_obj(data, player) player = Player.updatePlayer(session, player) response = convertToJson({'operation' : 'update', 'table' : 'Players', 'data' : player}) playersSubscribers = set(filter(removeClosedConnection, playersSubscribers)) for subscriber in playersSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['playerId']) == False: print('Not all parameters were provided for DELETE in Players') await websocket.send(convertToJson({'error' : 'Invalid request'})) return player = Player.deletePlayer(session, request['data']['playerId']) response = convertToJson({'operation' : 'delete', 'table' : 'Players', 'data' : player}) playersSubscribers = set(filter(removeClosedConnection, playersSubscribers)) for subscriber in playersSubscribers: await subscriber.send(response)
async def updatePlayers(session, playersConnected): players = Player.getPlayers(session) response = convertToJson({'operation' : 'get', 'table' : 'Players', 'data' : players}) for player in filterOpenedConnectionPlayers(playersConnected): await player['socket'].send(response)