def _updateConferenceObject(self, request): """Updates Conference Object """ user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException( 'Authorization required') user_id = getUserId(user) # Copy ConferenceForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) \ for field in request.all_fields()} # Update existing conference conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() # Check that conference exists if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' \ % request.websafeConferenceKey) # Check that user is owner if user_id != conf.organizerUserId: raise endpoints.ForbiddenException( 'Only the owner can update the conference.') # Not getting all the fields, so don't create a new object; just # Copy relevant fields from ConferenceForm to Conference object for field in request.all_fields(): data = getattr(request, field.name) # only copy fields where we get data if data not in (None, []): # special handling for dates (convert string to Date) if field.name in ('startDate', 'endDate'): data = datetime.strptime(data, "%Y-%m-%d").date() if field.name == 'startDate': conf.month = data.month # write to Conference object setattr(conf, field.name, data) conf.put() prof = ndb.Key(Profile, user_id).get() return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
def retrieve(self, request): """Retrieves content from a storage location.""" content = None key = None offset = request.offset # try the memcache memcache_entry = memcache.get( request.digest, namespace='table_%s' % request.namespace.namespace) if memcache_entry is not None: content = memcache_entry found = 'memcache' else: key = entry_key_or_error(request.namespace.namespace, request.digest) stored = key.get() if stored is None: logging.debug('%s', request.digest) raise endpoints.NotFoundException('Unable to retrieve the entry.') content = stored.content # will be None if entity is in GCS found = 'inline' # Return and log stats here if something has been found. if content is not None: # make sure that offset is acceptable logging.debug('%s', request.digest) if offset < 0 or offset > len(content): raise endpoints.BadRequestException( 'Invalid offset %d. Offset must be between 0 and content length.' % offset) stats.add_entry(stats.RETURN, len(content) - offset, found) return RetrievedContent(content=content[offset:]) # The data is in GS; log stats and return the URL. if offset < 0 or offset > stored.compressed_size: logging.debug('%s', request.digest) raise endpoints.BadRequestException( 'Invalid offset %d. Offset must be between 0 and content length.' % offset) stats.add_entry( stats.RETURN, stored.compressed_size - offset, 'GS; %s' % stored.key.id()) return RetrievedContent(url=self.gs_url_signer.get_download_url( filename=key.id(), expiration=DEFAULT_LINK_EXPIRATION))
def _conferenceRegistration(self, request, reg=True): """Register or unregister user for selected conference.""" retval = None prof = self._getProfileFromUser() # get user Profile # check if conf exists given websafeConfKey # get conference; check that it exists wsck = request.websafeConferenceKey conf = ndb.Key(urlsafe=wsck).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % wsck) # register if reg: # check if user already registered otherwise add if wsck in prof.conferenceKeysToAttend: raise ConflictException( "You have already registered for this conference") # check if seats avail if conf.seatsAvailable <= 0: raise ConflictException("There are no seats available.") # register user, take away one seat prof.conferenceKeysToAttend.append(wsck) conf.seatsAvailable -= 1 retval = True # unregister else: # check if user already registered if wsck in prof.conferenceKeysToAttend: # unregister user, add back one seat prof.conferenceKeysToAttend.remove(wsck) conf.seatsAvailable += 1 retval = True else: retval = False # write things back to the datastore & return prof.put() conf.put() return BooleanMessage(data=retval)
def get_speaker(self, websafe_speaker_key): """Get skeaper, given a key. Args: websafe_speaker_key (string) Raises: endpoints.NotFoundException """ # See comment about exceptions in get_conference method try: speaker = ndb.Key(urlsafe = websafe_speaker_key).get() except: speaker = None if not speaker: raise endpoints.NotFoundException( 'No speaker found with key: %s' % websafe_speaker_key) return speaker
def Update(self, request): """Updates an existing device action. Body: Device action data Parameters: device_action_id: Device action ID """ device_action = mtt_messages.ConvertToKey( ndb_models.DeviceAction, request.device_action_id).get() if not device_action: raise endpoints.NotFoundException( 'no device action found for ID %s' % request.device_action_id) request.id = request.device_action_id device_action = mtt_messages.Convert(request, ndb_models.DeviceAction, mtt_messages.DeviceAction) device_action.put() return mtt_messages.Convert(device_action, mtt_messages.DeviceAction)
def get_user_games(self, request): """Returns all of an individual User's active games""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') user = user.key # chore: figure out why I don't have to call fetch on the # queries for games and scores above - thought this just # built a query object and didn't actually query the database # without .fetch() or .get() - see the link below...when used # as an iterator the query instance returns results when it is # iterated over # http://stackoverflow.com/questions/15410609/google-app-engine-ndb-need-to-fetch-after-query games = Game.query( Game.game_over == False, ndb.OR(Game.user_name_x == user, Game.user_name_o == user)) return GameForms(items=[game.to_form("active game") for game in games])
def get_user_games(self, request): """Return the state of games for user.""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException('User not exist!') games = Game.query( ndb.OR(Game.user1 == user.key, Game.user2 == user.key)) game_forms = list() for game in games: if game.moves % 2 == 0: game_forms.append( game.to_form('It is player1 {} to make a move!'.format( game.user1.get().name))) else: game_forms.append( game.to_form('It is player2 {} to make a move!'.format( game.user2.get().name))) return GameForms(game_forms=game_forms)
def get_game_history(self, request): """Return the current game history with the help of urlsafe in utils.py. Matches the strings returned by urlsafe """ game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: if not game.winner1 == True or game.winner2 == True or len( game.moves) == 9: taskqueue.add(params={ 'nameplayer1': game.player1.get().name, 'emailplayer1': game.player1.get().email, 'nameplayer2': game.player2.get().name, 'emailplayer2': game.player2.get().email }, url='/tasks/cache_incomplete_games') return game.move_to_form('Here we go. The history of the game') else: raise endpoints.NotFoundException('Game not found!')
def new_game(self, request): """Create a new game""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') try: print user.key print user.email u_key = ndb.Key(User, user.email) # print hash(u_key) game_id = RPS.allocate_ids(size=1, parent=u_key)[0] game_key = ndb.Key(RPS, game_id, parent=u_key) game = RPS.new_game(game_key, user.key, request.total_rounds) game.put() except: pass return game.to_form('Limber Up! Its rock paper scissor time!')
def getSessionsInWishlist(self, request): """Query for all the sessions in a conference that the user is interested in.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException( 'You must be logged in to use this method.') user_id = getUserId(user) prof = ndb.Key(Profile, user_id).get() if not prof: raise endpoints.NotFoundException('Profile not found.') wishlist = prof.wishList wishlist_keys = [ndb.Key(urlsafe=wish) for wish in wishlist] wishlist_sessions = ndb.get_multi(wishlist_keys) return SessionForms(items=[ self._copySessionToForm(wish) for wish in wishlist_sessions ])
def getConferenceSessions(self, request): """ Given a conference return all sessions (by websafeConferenceKey).""" # get Conference object from request; bail if not found conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) # create ancestor query for all key matches for this conference # get list of sessions sessions = Session.query(ancestor=ndb.Key( Conference, request.websafeConferenceKey)).fetch() # return set of SessionForms objects per session return SessionForms( items=[self._copySessionToForm(session) for session in sessions] )
def getConferenceSessionsByTime(self, request): """Return all sessions starting between timeStart and timeEnd""" # #get conference key conference_key = ndb.Key(urlsafe=request.websafeConferenceKey) if not conference_key: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) # get sessions for conference in a time range sessions_all = Session.query(ancestor=conference_key) sessions_ByTime = sessions_all.filter( ndb.AND(Session.timeStart >= request.timeStart, Session.timeStart <= request.timeEnd)) return SessionForms( items=[self._copySessionToForm(sess) for sess in sessions_ByTime])
def get_user_games(self, request): """Returns all games for a given user""" # check to see if username is valid user = check_user_exists(request.username) games = Game.query(ndb.AND(Game.player_names == user.name)) error_msg = 'No games found for user {}'.format(user.name) # get active_only games by filtering game_over = false if request.active_only: games = games.filter(Game.game_over != request.active_only) error_msg = 'No active games found for user {}'.format(user.name) if games.count(): return AllGamesForm(games=[game.to_form("n/a") for game in games]) else: raise endpoints.NotFoundException(error_msg)
def getConferenceSessionsByType(self, request): """Given a conference, return all sessions of a specified type (eg lecture, keynote, workshop) """ #get conference key conference_key = ndb.Key(urlsafe=request.websafeConferenceKey) if not conference_key: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) sessions_all = Session.query(ancestor=conference_key) sessions_ByType = sessions_all.filter( Session.typeOfSession == request.typeOfSession.name) return SessionForms( items=[self._copySessionToForm(sess) for sess in sessions_ByType])
def get_user_rankings(self, request): """Get users win rate ranking. Args: request: None. Returns: UserForms: All the fields in UserForm that contains information about each user, sorted by the highest win ratio. If 2 players have the same win ratio, the player with fewer games played wins. Raises: endpoints.NotFoundException: If no users with wins > 0 can be found. """ users = User.query(User.win_ratio > 0.0).order(-User.win_ratio, User.total_played) # Raise an exception if no users are found. if not users: raise endpoints.NotFoundException('Cannot find any users!') return UserForms(items=[user.to_form() for user in users])
def Update(self, request): """Updates a test suite. Body: Test suite data Parameters: test_id: Test ID """ test = mtt_messages.ConvertToKey(ndb_models.Test, request.test_id).get() if not test: raise endpoints.NotFoundException('no test found for ID %s' % request.test_id) request.id = request.test_id test = mtt_messages.Convert(request, ndb_models.Test, mtt_messages.Test) test.put() return mtt_messages.Convert(test, mtt_messages.Test)
def get_user_games(self, request): """Return a user's active games ordered by the time each game was created""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A user with that name does not exist!') # Get a list of all of a user's games games = Game.query( Game.user == user.key).order(-Game.time_created).fetch() # Filter out completed and cancelled games; return what's left game_lst = [] for g in games: if not g.game_over: if not g.cancelled: game_lst.append(g) return GameForms(items=[g.to_form_user_games() for g in game_lst])
def retrieve_user(self, request): user_key_id = request.id # logging.info('USE ID '+str(user_key_id)) user_key = ndb.Key(urlsafe=str(user_key_id)) # logging.info('KEY '+str(user_key)) userDb = user_key.get() # logging.info('DB '+str(userDb)) user = None if userDb is not None: user = User(user_id=userDb.user_id, email=userDb.email, key=str(userDb.key.id()), strava_id=userDb.strava_id, strava_token=userDb.strava_token) else: message = 'No user with key "%s" exists.' % user_key_id raise endpoints.NotFoundException(message) return user
def getConferenceSessionsByType(self, request): """Return sessions for selected conference and session type (by websafeConferenceKey).""" # get conference key conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) # create ancestor query for all key matches for this conference sessions = Session.query(ancestor=conf.key) # filter sessions for those of matching type. filteredSessions = sessions.filter( Session.typeOfSession == request.typeOfSession) # return set of Sessionform objects per Session return SessionForms( items=[self._copySessionToForm(sess) for sess in filteredSessions])
def cancel_game(self, request): """Allows the user to cancel a game""" game = get_by_urlsafe(request.urlsafe_game_key, RPS) if game: game_initiator = User.query(User.key == game.user).get().name if game_initiator != getattr(request, "user_name"): raise endpoints.ForbiddenException( 'Not authorized to cancel game.'.format(game_initiator)) if game.game_over: return game.to_form('Game is already over. Cannot cancel.') elif game.game_canceled: return game.to_form('Game already canceled.') else: game.game_canceled = True game.put() return game.to_form('Game canceled.') else: raise endpoints.NotFoundException('Game not found!')
def scan_product(self, request): ''' Retrieve a product based on a barcode (scanning the product) ''' # lookup product by barcode products = Product.lookup_barcode(request.barcode) # retrieve the user user = User.get_by_urlsafe_key(request.user) if not user: message = 'No user with the key "%s" exists.' % request.user raise endpoints.NotFoundException(message) # register this request as a scanning Scanning.create(request.barcode, products, user) # build and return the response return ProductHelper.create_collection(products, user)
def getConferenceSessions(self, request): """Given a conference, returns all sessions.""" # fetch conference conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() # check that conference exists if not conf: raise endpoints.NotFoundException( 'No Conference found with key: %s' % request.websafeConferenceKey) # create ancestor query for all key matches to conference sessions = Session.query(ancestor=ndb.Key(Conference, conf.key.id())) # return set of SessionForm objects per Session return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def get_scanned_products(self, request): ''' Retrieve user's scanned products ''' user = User.get_by_urlsafe_key(request.user_key) if not user: message = 'No user with the key "%s" exists.' % request.user_key raise endpoints.NotFoundException(message) products, next_cursor, more = UsersHelper.fetch_scanned_products( user, request.cursor, request.size) cursor = '' if next_cursor: cursor = next_cursor.urlsafe() return UsersHelper.create_scanned_products_collection( user, products, cursor, more)
def new_game(self, request): """Creates new game""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') try: game = Game.new_game(user.key, request.length, request.attempts) except ValueError: raise endpoints.BadRequestException( 'Attempts must be between 3 and' '10 and length between 5 and 10') # Use a task queue to update the average attempts remaining. # This operation is not needed to complete the creation of a new game # so it is performed out of sequence. taskqueue.add(url='/tasks/cache_average_attempts') return game.to_form('Good luck playing Hangman!')
def cancel_game(self, request): """Cancel a game in progress and penalize player""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game and not game.game_over: game.attempts += 3 game.end_game(False) game.key.delete() return StringMessage( message= 'Game with key{} has been cancelled and player penalized 3 points' .format(request.urlsafe_game_key)) elif game and game.game_over: return StringMessage(message='Game with key{} is already over!'. format(request.urlsafe_game_key)) else: raise endpoints.NotFoundException( 'A game with this key was not found. It may have been cancelled.' )
def new_game(self, request): """Creates new game""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') try: game = Game.new_game(user.key, request.min, request.max, request.attempts) except ValueError: raise endpoints.BadRequestException('Maximum must be greater ' 'than minimum!') # Use a task queue to update the average attempts remaining. # This operation is not needed to complete the creation of a new game # so it is performed out of sequence. taskqueue.add(url='/tasks/cache_average_attempts') return game.to_form('Good luck pairing all the random strings!!')
def get_user_games(self, request): """ Return all of a user's active games, not include canceled games. """ user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name %s does not exist!' % request.user_name) active_games = Game.query(Game.user == user.key).filter( Game.game_over != True) forms = [] for game in active_games: if not game.is_canceled: forms.append(game.to_form("")) return GameForms(items=forms)
def getPreConferenceSessions(self, request): """ Returns a list of sessions happening before the main conference """ # Get current conference conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() # Make sure the conference exists if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) sessions = Session.query(ancestor=ndb.Key(Conference, conf.key.id()))\ .filter(Session.date < conf.startDate)\ .order(Session.date, Session.startTime) return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def _conferenceRegistration(self, request, reg=True): """Register or unregister user for selected conference.""" retval = None prof = self._getProfileFromUser() wsck = request.websafeConferenceKey conf = ndb.Key(urlsafe=wsck).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % wsck) if reg: if wsck in prof.conferenceKeysToAttend: raise ConflictException( "You have already registered for this conference") if conf.seatsAvailable <= 0: raise ConflictException( "There are no seats available.") prof.conferenceKeysToAttend.append(wsck) conf.seatsAvailable -= 1 retval = True else: if wsck in prof.conferenceKeysToAttend: prof.conferenceKeysToAttend.remove(wsck) conf.seatsAvailable += 1 retval = True else: retval = False prof.put() conf.put() return BooleanMessage(data=retval)
def createSession(self, request): """ Creates Session from given SESSION_POST_REQUEST_FOR_CONFERENCE and returns a SessionForm.""" # (SessionForm, websafeConferenceKey) -- open only to the organizer of the conference profile = self._getProfileFromUser() conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) if conf.key.parent().get() != profile: raise endpoints.UnauthorizedException( 'Session creation is open only to the organizer of the conference!' ) # copy SESSION_POST_REQUEST_FOR_CONFERENCE/ProtoRPC Message into dict data = { field.name: getattr(request, field.name) for field in request.all_fields() } session = Session(name=data['name'], parent=conf.key) # convert dates from strings to Date objects; set month based on start_date if data['dateTime']: session.date = data['dateTime'].date() session.time = data['dateTime'].time() if data['highlights']: session.highlights = data['highlights'] if data['typeOfSession']: session.typeOfSession = data['typeOfSession'] if data['duration']: session.duration = data['duration'] if data['speakers']: session.speakers = data['speakers'] session.put() if data['speakers']: session.speakers = data['speakers'] logging.debug( "Creating session with speakers, adding task to taskqueue.", str(session)) taskqueue.add(url='/tasks/add_featured_speaker', params={'sessionKeyUrlSafe': session.key.urlsafe()}) return self._copySessionToForm(session)