def addSessionToWishlist(self, request): """Adds conference to users wishlist.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) p_key = ndb.Key(urlsafe=request.sessionKey) print p_key wishItem = WishList(parent=p_key) #Assign the wishlist item to have both a sessionkey to get he session and the user_id to correctly call it #back uniquely to that user. wishItem.sessionKey = request.sessionKey wishItem.userID = user_id wishItem.put() # This is just setting up the message to return to the user websafeKey = StringMessage() websafeKey.data = "Successfully added to wishlist: " + request.sessionKey testQ = WishList.query() #Just return the message confirming that the session was added to the wishlist return websafeKey
def deleteSessionInWishlist(self, request): """Delete sessions in users wishlist.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # item = WishList.query(ndb.Key(urlsafe=request.sessionKey)) # item.delete() # key = ndb.Key(urlsafe=request.data) # print key # print "I just used the key" testQ = WishList.query() filtered = testQ.filter(WishList.sessionKey == request.data) # print filtered # p = testQ.filter(WishList.sessionKey == request.data and WishList.userID == user_id) for t in filtered: t.key.delete() websafeKey = StringMessage() # Fedback to user, confirming item in wishlist was deleted. websafeKey.data = "wishlist item deleted" return websafeKey
def addSessionToWishlist(self, request): """Create or update wishlist object, returning wishlist/request.""" # preload necessary data items user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') #get the key of the session session = ndb.Key(urlsafe=request.sessionKey) #get the profile of the current user currentUser = self._getProfileFromUser() sessions_in_Wishlist = currentUser.sessionWishlist if request.sessionKey in currentUser.sessionWishlist: msg = StringMessage(data="Session is already in your wishlist. This has not been added to avoid duplications") else: currentUser.sessionWishlist.append(request.sessionKey) msg = StringMessage(data="The session has been added to the wishlist") currentUser.put() return msg
def make_move(self, request): """Makes a move. User sends a request containing a guess.""" # retrieve the game with the urlsafe key, then the target game = get_by_urlsafe(request.urlsafe_game_key, Game) target = game.target if game.game_over: return game.to_form('Game already over!') if game.connect_4_turn == True: return StringMessage(message="make a connect four move!") if request.guess == game.answer: # connect four turn gets set to true and move is logged game.connect_4_turn = True game.new_round(game) game.moves.append(request.guess) game.move_count += 1 game.put() return StringMessage(message="correct") else: # computer makes a connect 4 move and move is logged game.new_round(game) cpu_move = random.choice(game.legal) game.player_move([cpu_move[0], cpu_move[1]], "player_2") game.moves.append("wrong guess, cpu move " + str(cpu_move[0]) + " " + str(cpu_move[1])) game.move_count += 1 game.put() return StringMessage(message="incorrect")
def getFeaturedSpeaker(self, request): """Returns the featured speaker stored in memcache""" speaker, sessionName = memcache.get('featuredSpeaker') or ('','') # copy the list to a form form = StringMessage(data=speaker+' - '+sessionName) form.check_initialized() return form
def resetGameState(self, request): # Remove move ownership for all users # Resets move availablities to True game_id = request.game_id # for the moment, resets every move for provided game_id moves = Move.query().fetch() moves_deleted = Move.query(Move.game_id == game_id).fetch() game = Game.query(Game.game_id == game_id).get() if game == None: return StringMessage( message="No Game found for ID: {0} ".format(game_id)) print("game id is {0} {1}".format(game_id, moves[0].game_id)) # Deleting Game game.key.delete() # Deleting Moves for move in moves_deleted: print("Deleting moves, {0}".format(move)) move.key.delete() return StringMessage( message="Game Reset Complete, deleted {0} moves for Game: {1} ". format(len(moves_deleted), game_id))
def getBalance(self, request): p_key = ndb.Key(UserDetails, request.phoneNumber) result = p_key.get() if result: return StringMessage(data=str(result.balance)) else: return StringMessage(data="Phone number does not exist")
def cancel_game(self, request): """Cancel a game in progress""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over: return StringMessage(message="Can not cancel a completed game!") game.key.delete() return StringMessage( message="Game {} is deleted!".format(request.urlsafe_game_key))
def cancel_game(self,request): """Cancel an active game by deleting it""" game = get_by_urlsafe(request.urlsafe_game_key,Game) if game: if game.game_over: return StringMessage(message = 'This game has ended') else: game.key.delete() return StringMessage(message = 'Game Canceled!') else: return StringMessage(message = "Game doesn't exist")
def cancel_game(self, request): """Set the game status to cancelled.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.status != 'NEW': return StringMessage(message='Game already over or cancelled.') game.status = 'CANCELLED' game.put() return StringMessage(message='Game cancelled!') else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Return the current game state.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if game.game_over == True: return StringMessage( message='Game is over and can\'t be deleted!') game.key.delete() return StringMessage(message='removed!') else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): '''Cancel an active game''' game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException("We could not find your game!") if game.game_over == False: # NOQA game.key.delete() return StringMessage(message="Game cancelled!") else: return StringMessage(message="You can't delete a completed game!")
def cancel_game(self, request): """Cancel a game in progress""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game and not game.game_over: game.end_game(won=False) game.key.delete() return StringMessage(message='Game {} has been cancelled'.format( request.urlsafe_game_key)) elif game and game.game_over: return StringMessage(message='Game {} is already over!'.format( request.urlsafe_game_key)) else: raise endpoints.NotFoundException('Game not found.')
def cancel_trivia_game(self, request): """Cancel an active game. Requires urlsafe_trivia_game_key.""" game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame) if game: if game.game_over: return StringMessage(message='Game is over, cannot cancel!') game.clear_game() game.key.delete() return StringMessage(message='Game cancelled!') else: raise endpoints.NotFoundException('Game not found!')
def cancel_game(self, request): """Cancel an incompleted game""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if not game.game_over: game.key.delete() return StringMessage( message='Game {} cancelled!'.format(game.key.urlsafe())) else: return StringMessage( message='Game is over, cannot be cancelled!'.format( game.key.urlsafe())) else: raise endpoints.NotFoundException('Game not found!')
def get_user_rankings(self, request): """Returns ranking of a user""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') rank = 1 query = Score.query().filter(Score.won == True).order(Score.guesses).fetch() for score in query: if user.key == score.user: msg = str(rank) return StringMessage(message=msg) else: rank += 1 msg = 'User not ranked' return StringMessage(message=msg)
def getSpeakerAnnouncement(self, request): """Return new speaker from memcache.""" # return an existing announcement from Memcache or an empty string. announcement = memcache.get(MEMCACHE_SPEAKER_KEY) if not announcement: announcement = "" return StringMessage(data=announcement)
def get_game_history(self, request): """Returns a summary of a game's guesses.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') return StringMessage(message=str(game.history))
def getFeaturedSpeaker(self, request): """Return speaker and session names from memcache.""" # return an existing announcement from Memcache or an empty string. featured_speaker = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY) if not featured_speaker: featured_speaker = "" return StringMessage(data=featured_speaker)
def getFeaturedSpeaker(self, request): """Return Featured Speaker from memcache""" featured = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY) if not featured: featured = "" return StringMessage(data=featured)
def deleteSession(self, request): """Delete a session""" # Get current user user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # Get Session Key session_key = ndb.Key(urlsafe=request.websafeSessionKey) # check that session exists if not session_key: raise endpoints.NotFoundException('No session found with key: %s' % request.websafeSessionKey) # Check that user matches conference organizer conference_key = session_key.get().conferenceKey if user_id != conference_key.get().organizerUserId: raise ConflictException( 'Only the conference organizer can delete sessions for the conference' ) session_key.delete() # Delete session_key from profile wishlists profiles = Profile.query() for profile in profiles: if session_key in profile.sessionWishlist: profile.sessionWishlist.remove(session_key) profile.put() return StringMessage(data='Session deleted')
def cancel_game(self, request): game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over is True: raise endpoints.ForbiddenException( 'You can not cancel this game as it is already over!') # Save the game. # A game with no winner and with game_over=True is a cancelled game. game.game_over = True game.put() # Decrement active games taskqueue.add(url='/tasks/decrement_active_games') message = "The game was cancelled successfuly." # Update game history game_history = GameHistory.query(ancestor=game.key).get() game_history.history.append(game) game_history.messages.append(message) game_history.put() return StringMessage(message=message)
def getFeaturedSpeaker(self, request): """Return Featured Speaker from memcache.""" # return an existing Featured Speaker from Memcache or an empty string. featured = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY) if not featured: featured = "" return StringMessage(data=featured)
def getAnnouncement(self, request): """Return Announcement from memcache.""" announcement = "" if memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY): announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY) return StringMessage(data=announcement)
def get_users(self, request): """List all the registered user name and email""" users = User.query() strs = "" for user in users: strs += "(%s, %s)" % (user.name, user.email) return StringMessage(message=strs)
def get_featured_speaker(self): """Return featured speaker announcement from memcache. Returns: Announcement message (string) """ return StringMessage(data = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY) or "")
def make_connect_four_move(self, request): """player makes a connect four move""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over == True: return StringMessage(message="Game is over") if game.connect_4_turn == False: return StringMessage(message="Guess a word!") # Player makes connect four move, move is logged game.player_move([request.row, request.slot], "player_1") game.moves.append(str(request.row) + " " + str(request.slot)) game.move_count += 1 game.connect_4_turn = False game.put() return StringMessage(message=game.connect_four_response)
def _get_players_in_game(game_id): moves = Move.query(Move.game_id == game_id).fetch() if len(moves) == 0: return StringMessage( message="Invalid move parameters. no game found") print("Getting players in game...") user_ids = [] for move in moves: user_id = move.user_id # print("checking for ID: {0}".format( user_id) ) if user_id not in user_ids and user_id != None: # print("ID: {0} was inserted".format( user_id) ) user_ids.append(user_id) print(user_ids) if len(user_ids) == 2: player1 = user_ids[0] player2 = user_ids[1] elif len(user_ids) == 1: player1 = user_ids[0] player2 = None else: player1 = None player2 = None print(player2, player1) return [player1, player2]
def get_user_rankings(self, request): """ The ranking is defined by the ratio of sum(score)/(2*game) """ scores = Score.query() scores_list_dict = defaultdict(list) for score in scores: scores_list_dict[score.user.get().name].append( score.user_score_to_int()) scores_list_dict = dict(scores_list_dict) performances_dict = {} for k, v in scores_list_dict.iteritems(): performance = sum(v) / (2 * len(v)) performances_dict[k] = performance performances_list_sorted = sorted(performances_dict.items(), key=operator.itemgetter(1), reverse=True)[0:request.max_number] strs = json.dumps(performances_list_sorted) return StringMessage(message=strs)
def getAnnouncement(self, request): """Return Announcement from memcache.""" # TODO 1 # return an existing announcement from Memcache or an empty string. announcement = "" return StringMessage(data=announcement)
def getAnnouncement(self, request): """Return Announcement from memcache.""" # return an existing announcement from Memcache or an empty string. announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY) if not announcement: announcement = "" return StringMessage(data=announcement)
def getFeaturedSpeaker(self, request): """ Return featured speakers from memcache as a JSON string """ memcache_key = MEMCACHE_FEATURED_KEY_PREFIX + request.websafeKey cache = memcache.get(memcache_key) featured = cache or "{}" return StringMessage(data=featured)
def getAnnouncement(self, request): """Return Announcement from memcache.""" self._cacheAnnouncement() announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY) if not announcement: announcement = "" return StringMessage(data=announcement)
def cancel_game(self, request): """ allows users to cancel a game in progress. """ msg = StringMessage() game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: msg.message = "The game is already canceled" return msg if game.game_over: msg.message = "You can't cancel a finished game" return msg user = User.query(User.name == request.user_name).get() if not user or game.user!= user.key: msg.message = "You are not allowed to cancel other's game" else: if game.game_over: msg.message = "Game was already over, you can't cancel it" else: game.key.delete() msg.message = "Game canceled." return msg