def giveAttendenceToStudent(self, request):
     user = endpoints.get_current_user()
     user_id = helper.getUserId()
     registeredUser = helper.getRegisteredUser()
     if not registeredUser:
         raise endpoints.ForbiddenException("Not Allowed to update user")
     if not (registeredUser.isAdmin == True or registeredUser.isOwner
             == True or registeredUser.isTeacher == True):
         raise endpoints.ForbiddenException("Not Allowed to update user")
     namespace_manager.set_namespace(self._getNamespace(registeredUser))
     print request.studentWebSafeKey
     studentAttendenceKey = ndb.Key(
         StudentAttendence,
         request.date,
         parent=ndb.Key(urlsafe=request.studentWebSafeKey))
     print studentAttendenceKey
     studentAttendence = studentAttendenceKey.get()
     print studentAttendence
     if not studentAttendence:
         studentAttendence = StudentAttendence()
     print studentAttendence
     studentAttendence.isPresent = True if request.isPresent == True else False
     studentAttendence.date = datetime.datetime.strptime(
         request.date, '%d-%m-%Y').date()
     studentAttendence.employeeKey = registeredUser.key
     studentAttendence.key = studentAttendenceKey
     studentAttendence.studentKey = ndb.Key(
         urlsafe=request.studentWebSafeKey)
     #         student = ndb.Key(urlsafe=request.studentWebSafeKey).get()
     #         attendencePercentage = StudentAttendence.all()
     #         attendencePercentage = attendencePercentage.ancestor(ndb.Key(urlsafe=request.studentWebSafeKey))
     studentAttendence1 = StudentAttendence.query(ancestor=ndb.Key(
         urlsafe=request.studentWebSafeKey))
     totalAttendence = 0.0
     totalPresent = 0.0
     for s in studentAttendence1:
         totalAttendence = totalAttendence + 1
         print s.isPresent
         if s.isPresent == True:
             totalPresent = totalPresent + 1
     print totalAttendence
     print totalPresent
     attendencePercentage = (totalPresent / totalAttendence) * 100
     student = ndb.Key(urlsafe=request.studentWebSafeKey).get()
     student.attendencePercentage = attendencePercentage
     kind = []
     kind.append(student)
     kind.append(studentAttendence)
     self._saveKinds(kind)
     print datetime.date.today()
     print studentAttendence
     return message_types.VoidMessage()
示例#2
0
 def make_move(self, request):
     """Makes a move. Returns the current games state with message"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game.finished_status:
         raise endpoints.ForbiddenException("Game already over")
     else:
         position = request.position
         position_str = str(position)
         if position_str.isdigit():
             if position < 10 and position > 0:
                 if position not in game.moves:
                     i = len(game.moves)
                     if i % 2 == 0:
                         game.player1_position.append(position)
                         game.moves.append(position)
                         game.available_positions[position - 1] = 0
                         game.put()
                         still_available = len(game.moves)
                         check = win_checker(game.player1_position)
                         if check == "Player is the champ!":
                             game.end_of_game(True, False)
                             game.put()
                             return game.to_form("Player1 is the best")
                         elif i + 1 == 9:
                             game.finished_status = True
                             game.put()
                             return game.to_form("Draw")
                         else:
                             return game.to_form(check)
                     else:
                         game.player2_position.append(position)
                         game.moves.append(position)
                         game.available_positions[position - 1] = 0
                         game.put()
                         still_available = len(game.moves)
                         check = win_checker(game.player2_position)
                         if check == "Player is the champ!":
                             game.end_of_game(False, True)
                             game.put()
                             return game.to_form("Player2 is the best")
                         else:
                             return game.to_form(check)
                 else:
                     raise endpoints.BadRequestException(
                         "Position is already taken")
             else:
                 raise endpoints.BadRequestException(
                     "Position must be between 1 to 9")
         else:
             raise endpoints.ForbiddenException("Please type in a number")
    def getConferenceSessionsByType(self, request):
        """Get session by typeOfSession."""
        if not request.websafeConferenceKey:
            raise endpoints.ForbiddenException(
                'Requires websafeConferenceKey.')
        if not request.typeOfSession:
            raise endpoints.ForbiddenException('Requires typeOfSession.')
        # get parent key
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # query session by ancestor, filter by typeOfSession
        q = Session.query(ancestor=conf.key).filter(
            Session.typeOfSession == request.typeOfSession)

        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in q])
示例#4
0
    def cancel_game(self, request):
        """Cancel a game that is in progress."""
        """
        Args:
            request: The CANCEL_GAME_REQUEST object.
        Returns:
            A message that is sent to the client, saying that the
            game has been cancelled.
        Raises:
            endpoints.NotFoundException: If the game isn't found.
            endpoints.ForbiddenException: If the game is completed already it
            cannot be cancelled."""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        if not game:
            raise endpoints.NotFoundException('Game not found.')
        if game.game_over:
            raise endpoints.ForbiddenException(
                'Cannot cancel a completed game.')

        players = Player.query(ancestor=game.key)
        for player in players:
            player.key.delete()

        game.key.delete()
        return StringMessage(message='Your game was succesfully cancelled.')
示例#5
0
文件: api.py 项目: csarradet/fsndp4
 def enrolled_player_only_dec(*args, **kwargs):
     game = kwargs[DEC_KEYS.GAME]
     current_user = kwargs[DEC_KEYS.USER]
     if not current_user.key in game.player_keys:
         raise endpoints.ForbiddenException(
             'Only an enrolled player can perform that action')
     return func(*args, **kwargs)
示例#6
0
文件: api.py 项目: csarradet/fsndp4
 def active_player_only_dec(*args, **kwargs):
     game = kwargs[DEC_KEYS.GAME]
     current_user = kwargs[DEC_KEYS.USER]
     if not current_user.key == game.active_player_key:
         raise endpoints.ForbiddenException(
             'Only the active player can perform that action')
     return func(*args, **kwargs)
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("Session'name' field required")

        # fetch and check conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'Conference not found for key: %s' % request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'You need to be the owner to add sessions.')

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        # convert dates from strings to Date objects
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()

        # convert time from strings to Time object (date-independent)
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()

        # make session key from conf key
        p_key = conf.key

        # allocate new session id with conf
        s_id = Session.allocate_ids(size=1, parent=p_key)[0]
        s_key = ndb.Key(Session, s_id, parent=p_key)
        data['key'] = s_key
        data['organizerUserId'] = user_id
        del data['websafeConferenceKey']
        del data['websafeKey']

        Session(**data).put()

        # Add to the task queue a task for setting cache
        # Task will check if speaker is in more than one session
        # If yes, will cache results

        taskqueue.add(
            params={
                'confKey': p_key,
                'speaker': data['speaker']
            },
            url='/tasks/set_featured_speaker'
        )

        return request
示例#8
0
    def _updateConferenceObject(self, request):
        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
        c_key = validate_conf_key(request.websafeConferenceKey)
        conf = c_key.get()
        # 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'))
示例#9
0
    def JoinGame(self, player):
        currentUser = endpoints.get_current_user()

        query = Player.query(Player.gameId == player.gameId,
                             Player.user == currentUser)

        if (query.get(keys_only=True)):
            raise endpoints.ForbiddenException("You are already in this game.")

        game = player.gameKey.get()

        if (game is None):
            raise endpoints.NotFoundException("Game not found")

        players = Player.query(Player.gameId == player.gameId)

        if (game.status != GAME_STATUS_PENDING
                or (players.count() == game.maxPlayers)):
            raise endpoints.BadRequestException(
                "Game %s is not currently accepting new players" %
                game.gameName)

        player.user = currentUser
        player.hand = []
        player.score = 0
        player.position = -1
        player.alert = NO_ALERTS
        player.isCzar = False

        player.put()

        return player
示例#10
0
    def removeFeaturedArticle(self, request):
        """Remove an article from featured articles (Favorites of authorID 0)"""

        user_author = self._getAuthorFromUser()

        if not user_author:
            raise endpoints.UnauthorizedException(
                '%s is not an author of any articles or comments' %
                user_author.nickname())

        userRights = getattr(UserRights, user_author.userRights)

        if userRights < UserRights.FELLOW:
            raise endpoints.ForbiddenException(
                "Only an administrator or fellow can remove a featured article."
            )
        self._checkKey(request.websafeArticleKey, 'Article')

        favoritesAuthor = Author.query()\
            .filter(Author.authorID=='0')\
            .get()

        if not request.websafeArticleKey in favoritesAuthor.favoriteArticles:
            raise endpoints.NotFoundException(
                "Article is not a featured article")

        # find and delete the article key
        idx = favoritesAuthor.favoriteArticles.index(request.websafeArticleKey)
        del favoritesAuthor.favoriteArticles[idx]
        favoritesAuthor.put()

        return BooleanMessage(data=True)
示例#11
0
    def addFeaturedArticle(self, request):
        """Add an article to featured articles (Favorites of authorID 0)"""

        user_author = self._getAuthorFromUser()

        if not user_author:
            raise endpoints.UnauthorizedException(
                '%s is not an author of any articles or comments' %
                user_author.nickname())

        userRights = getattr(UserRights, user_author.userRights)

        if userRights < UserRights.FELLOW:
            raise endpoints.ForbiddenException(
                "Only an administrator or fellow can add a featured article.")
        self._checkKey(request.websafeArticleKey, 'Article')

        favoritesAuthor = Author.query(Author.authorID == '0').get()

        if request.websafeArticleKey in favoritesAuthor.favoriteArticles:
            raise endpoints.BadRequestException(
                "Article is already a featured article")

        favoritesAuthor.favoriteArticles.append(request.websafeArticleKey)
        favoritesAuthor.put()

        return BooleanMessage(data=True)
示例#12
0
    def updateMyArticle(self, request):
        """Update Article object, returning ArticleForm/request."""

        author = self._getAuthorFromUser()

        # get existing Article
        article = self._checkKey(request.websafeArticleKey, 'Article').get()

        # check that user is owner
        if author.key != article.key.parent():
            raise endpoints.ForbiddenException(
                'Only the owner can update the Article.')

        # copy ArticleForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ArticleForm to Article object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # write to Article object
                setattr(article, field.name, data)

        article.put()
        return self._copyArticleToForm(article, author=author)
    def _updateSessionObject(self, request):
        """Update Session object, returning SessionForm"""
        # User authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Copy SessionForm Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}

        # get session object from Datastore
        session = self._getDataStoreObject(request.websafeSessionKey)

        # User Authorization
        conf = session.key.parent().get()
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the session.')

        # copy relevant fields from Session Form to Session object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                if field.name == 'date':
                    data = datetime.strptime(data[:10], "%Y-%m-%d").date()
                if field.name == 'startTime':
                    data = datetime.strptime(data, "%H:%M").time()
                setattr(session, field.name, data)
        session.put()
        return self._copySessionToForm(session)
示例#14
0
    def deleteAllConferenceSessions(self, request):
        """Delete all sessions (by websafeConferenceKey)."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        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.')

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        sessions = Session.query(ancestor=conf.key)
        for session in sessions:
            session.key.delete()
        return message_types.VoidMessage()
示例#15
0
    def make_game_easier(self, request):
        """Given a number, automatically match same count of pairs and return match histories"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found!')
        if game.game_over:
            raise endpoints.ForbiddenException('Illegal action: Game is already over.')

        hint_num = request.hint_num
        if hint_num <= 0:
            raise endpoints.ForbiddenException('Illegal action: Can not receive a negative number.')
        if hint_num * 2 >= 52 - game.matched:
            raise endpoints.ForbiddenException('Illegal action: Can not use hint to win, try a smaller number.')

        hint_histories = GameLogic.make_game_easier(game=game, hint_num=hint_num)
        return HistoryForms(items=[h.to_form() for h in hint_histories])
    def getAttenderByConference(self, request):
        """ Query for all registered users in a specified conference. (This query
        is only open to conference organizer) """
        # make sure that the user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user, id_type="oauth")

        # get the conference model
        wsck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=wsck).get()

        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                "No conference found with key: %s" %
                request.websafeConferenceKey)

        # check if the user is the organizer of the conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                "Only the conference organizer can query for attendees.")

        # apply the filter
        query_result = Profile.query(
            Profile.conferenceKeysToAttend.IN([
                wsck,
            ]))

        # return the ProfileForms
        return ProfileForms(
            items=[self._copyProfileToForm(pf) for pf in query_result])
示例#17
0
    def get_task_def(self, request):
        """Returns a swarming task definition for a build request."""
        try:
            build_request = api.put_request_message_to_build_request(
                request.build_request)
            build_request = build_request.normalize()

            identity = auth.get_current_identity()
            if not acl.can_add_build(build_request.bucket):
                raise endpoints.ForbiddenException(
                    '%s cannot schedule builds in bucket %s' %
                    (identity, build_request.bucket))

            build = build_request.create_build(1, identity)
            bucket_cfg, _, task_def = (swarming.prepare_task_def_async(
                build, fake_build=True).get_result())
            task_def_json = json.dumps(task_def)

            res = GetTaskDefinitionResponseMessage(
                task_definition=task_def_json)
            if request.api_explorer_link != False:  # pragma: no branch
                res.api_explorer_link = shorten_url(
                    ('https://%s/_ah/api/explorer'
                     '#p/swarming/v1/swarming.tasks.new?resource=%s') %
                    (bucket_cfg.swarming.hostname,
                     urllib.quote(task_def_json)))
            return res
        except errors.InvalidInputError as ex:
            raise endpoints.BadRequestException('invalid build request: %s' %
                                                ex.message)
示例#18
0
    def _createSessionObject(self, request):
        """Create Session object from request and store in datastore."""
        # Check that user logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Get conference
        urlkey = request.websafeConferenceKey
        conf_key = ndb.Key(urlsafe=urlkey)
        conf = conf_key.get()

        # Check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % urlkey)

        # Check that logged in user is organizer
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the organizer can add sessions to the conference.')

        # Every session must have a name
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        # Copy SessionForm/ProtoRPC Message into dictionary
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        # Prepare all data for SessionForm
        del data['websafeConferenceKey']
        del data['websafeKey']
        del data['organizerDisplayName']
        data['organizerUserId'] = user_id

        # Convert dates from strings to DateTime objects
        if data['date']:
          data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()

        # Convert time from strings to DateTime objects
        if data['startTime']:
          data['startTime'] = datetime.strptime(data['startTime'],"%H:%M:%S").time()

        # Generate session id
        session_id = Session.allocate_ids(size=1, parent=conf_key)[0]

        # Generate session key with conference key as parent
        session_key = ndb.Key(Session, session_id, parent=conf_key)
        data['key'] = session_key

        # Write to datastore
        Session(**data).put()


        # Make announcement for featured speaker via task queue.
        speaker = data['speaker']
        taskqueue.add(params={'speaker': speaker, 'websafeConferenceKey': urlkey}, url='/tasks/set_session_announcement')

        return self._copySessionToForm(session_key.get())
示例#19
0
        def wrapper(*args, **kwargs):
            """Wrapper for auth check decorator."""
            if constants.ON_LOCAL:
                logging.info(
                    'Application is running locally. Skipping all auth checks.'
                )
                return function_without_auth_check(*args, **kwargs)

            # Get logged in user.
            try:
                user_email = user_lib.get_user_email()
            except user_lib.UserNotFound as err:
                raise endpoints.UnauthorizedException(str(err))
            # Only allow domain users.
            _forbid_non_domain_users(user_email)

            # If there are no specified permissions, continue with the function.
            if not permission:
                return function_without_auth_check(*args, **kwargs)

            # If there are permissions get the datastore user and compare permissions.
            datastore_user = user_model.User.get_user(user_email)
            if datastore_user.superadmin or (
                    permission in datastore_user.get_permissions()):
                return function_without_auth_check(*args, **kwargs)

            # Logged in user does not have correct permissions.
            raise endpoints.ForbiddenException(_FORBIDDEN_MSG)
示例#20
0
    def __prep_new_session(session_form):
        """
        Prepare a new Session instance, validating Conference and User details
        :param session_form:
        :return: Session ready for processing of speakers
        """
        if not isinstance(session_form, SessionForm):
            raise TypeError('expected SessionForm')

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = get_user_id(user)

        if not session_form.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # fetch the key of the ancestor conference
        conf_key = ndb.Key(urlsafe=session_form.websafeConfKey)
        conf = conf_key.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                session_form.websafeConfKey)

        # check that user is conference owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the conference owner can create sessions.')

        # create Session and set up the parent key
        return Session.from_form(session_form)
示例#21
0
 def wrapper(service, *args, **kwargs):
     try:
         initialize_request_auth(service.request_state.remote_address,
                                 service.request_state.headers)
         return func(service, *args, **kwargs)
     except endpoints.BadRequestException as e:
         # Useful to debug HTTP 400s.
         logging.warning('%s', e, exc_info=True)
         raise
     except api.AuthenticationError as ex:
         logging.warning(
             'Authentication error.\n%s\nPeer: %s\nIP: %s\nOrigin: %s',
             ex.message,
             api.get_peer_identity().to_bytes(),
             service.request_state.remote_address,
             service.request_state.headers.get('Origin'))
         raise endpoints.UnauthorizedException(ex.message)
     except api.AuthorizationError as ex:
         logging.warning(
             'Authorization error.\n%s\nPeer: %s\nIP: %s\nOrigin: %s',
             ex.message,
             api.get_peer_identity().to_bytes(),
             service.request_state.remote_address,
             service.request_state.headers.get('Origin'))
         raise endpoints.ForbiddenException(ex.message)
    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)
示例#23
0
    def get(self, request):
        """Handles an incoming CatalogMachineRetrievalRequest."""
        user = auth.get_current_identity().to_bytes()
        logging.info(
            'Received CatalogMachineRetrievalRequest:\nUser: %s\n%s',
            user,
            request,
        )
        if acl.is_catalog_admin():
            if not request.backend:
                raise endpoints.BadRequestException(
                    'Backend unspecified by administrator')
        elif acl.is_backend_service():
            current_backend = acl.get_current_backend()
            if request.backend is None:
                request.backend = current_backend
            if request.backend != current_backend:
                raise endpoints.ForbiddenException('Mismatched backend')

        entry = models.CatalogMachineEntry.get(request.backend,
                                               request.hostname)
        if not entry:
            raise endpoints.NotFoundException('CatalogMachineEntry not found')

        response = rpc_messages.CatalogMachineRetrievalResponse(
            dimensions=entry.dimensions,
            policies=entry.policies,
            state=entry.state,
        )
        if entry.lease_expiration_ts:
            # datetime_to_timestamp returns microseconds, convert to seconds.
            response.lease_expiration_ts = utils.datetime_to_timestamp(
                entry.lease_expiration_ts) / 1000 / 1000
        return response
示例#24
0
    def createSession(self, request):
        """Create new session for a given conference"""

        # get user id + auth check
        user_id = self._getUserId()

        # check for required fields
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")
        if not request.date:
            raise endpoints.BadRequestException(
                "Session 'date' field required")
        if not request.startTime:
            raise endpoints.BadRequestException(
                "Session 'startTime' field required")

        # get the conference key using websafeConferenceKey
        confKey, conf = ConferenceApi._getKeyAndEntityFromWebsafeKeyOfType(
            request.websafeConferenceKey, Conference)

        # check that user is session creator is also the creator of the conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only creator of the conference can add sessions to it')

        # check that speaker keys are valid
        for speakerWebsafeKey in request.speakerKeys:
            speakerKey, speaker = ConferenceApi._getKeyAndEntityFromWebsafeKeyOfType(
                speakerWebsafeKey, Speaker)

        # start building a data dictionary
        data = {}
        data['name'] = request.name
        data['highlights'] = request.highlights
        data['speakerKeys'] = request.speakerKeys
        data['duration'] = request.duration
        data['typeOfSession'] = request.typeOfSession.name
        data['date'] = datetime.strptime(request.date[:10], '%Y-%m-%d').date()
        data['startTime'] = datetime.strptime(
            str(request.startTime)[:4], '%H%M').time()

        # create a custom unique key, with the conference key as ancestor
        s_id = Session.allocate_ids(size=1, parent=confKey)[0]
        s_key = ndb.Key(Session, s_id, parent=confKey)
        data['key'] = s_key

        # write session object to datastore
        session = Session(**data)
        session.put()

        # trigger a task to update featured speaker
        taskqueue.add(params={
            'websafeConferenceKey': request.websafeConferenceKey,
            'websafeSpeakerKeys': '&'.join(request.speakerKeys)
        },
                      url='/tasks/update_featured_speaker')

        # return SessionForm
        return self._copySessionToForm(session)
示例#25
0
    def _createSessionObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # get and check conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No Conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user owns conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the user can add sessions.')

        # copy SessionForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeKey']
        del data['websafeConferenceKey']

        # convert date from strings to Date object
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        # convert time from string to Time object
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H-%M").time()

        # generate Conference key based on Conference ID and Session
        # ID based on Conference key get Session Key from ID
        p_key = ndb.Key(Conference, conf.key.id())
        c_id = Session.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Session, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = user_id

        Session(**data).put()

        # check if speaker has other sessions; if so, add to memcache
        sessions = Session.query(Session.speaker == data['speaker'],
                                 ancestor=p_key)
        if len(list(sessions)) > 1:
            taskqueue.add(params={'speaker': data['speaker']},
                          url='/tasks/set_featured_speaker')

        return request
示例#26
0
    def _updateConferenceObject(self, request):
        user_id = check_auth()

        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            k = request.websafeConferenceKey
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % k)

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        for field in request.all_fields():
            data = getattr(request, field.name)
            if data not in (None, []):
                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'))
示例#27
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.sessionName:
            raise endpoints.BadRequestException("Session 'name' field required")

        # 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.')


        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        wsck = data['websafeConferenceKey']
        p_key = ndb.Key(Conference, request.websafeConferenceKey)
        c_id = Session.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Session, c_id, parent=p_key)
        
        data['startTime']= datetime.strptime(data['startTime'], '%H:%M:%S').time()

        data['date']= datetime.strptime(data['date'], '%Y-%m-%d').date()
      
        data['key'] = c_key
        data['websafeConferenceKey'] = request.websafeConferenceKey
        
        speaker_name = data['speaker']  
       
        #Query sessions by speaker and get all of the ones that are currently in the datastore and add them 
        #to the memcache
        sessions_by_speaker = Session.query(ndb.AND(Session.speaker == speaker_name, Session.websafeConferenceKey == request.websafeConferenceKey)).fetch()
        
        speaker_sessions = []
        
        speaker_sessions = FEATURED_SPEAKER.format(speaker_name, ','.join([session.sessionName for session in sessions_by_speaker]))
        
        print speaker_sessions 

        if len(sessions_by_speaker) >= 1:
            #add the speaker and the sessions they are in into the memcache
            self._speaker_to_memcache(speaker_sessions)
        else:
            print "this speaker has 0 sessions"
            
        #add the new session data to datastore
        Session(**data).put()
 
        return request
示例#28
0
    def make_move(self, request):
        """Makes a move. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game.game_over:
            raise endpoints.ForbiddenException(
                'Illegal action: Game is already over.')

        HANDS = ['gun', 'water', 'snake']
        if request.hand.lower() not in HANDS:
            raise endpoints.BadRequestException(
                'Select one of Snake Water Gun')

        player_hand = request.hand.lower()
        computer_hand = random.choice(HANDS)
        msg = 'Player "' + player_hand + '" vs ' + \
              'Computer "' + computer_hand + '", '

        if computer_hand == player_hand:
            result = 'Tie'
        elif computer_hand == 'water':
            if player_hand == 'snake':
                result = 'Player'
            elif player_hand == 'gun':
                result = 'Computer'
        elif computer_hand == 'snake':
            if player_hand == 'water':
                result = 'Computer'
            elif player_hand == 'gun':
                result = 'Player'
        elif computer_hand == 'gun':
            if player_hand == 'water':
                result = 'Player'
            elif player_hand == 'snake':
                result = 'Computer'

        if result == 'Player':
            message = msg + 'You win!'
            game.history.append(message)
            game.put()
            game.end_game(game=request.urlsafe_game_key, message=message,
                          player_hand=player_hand, computer_hand=computer_hand,
                          won=True)
            return game.to_form(message)
        elif result == 'Computer':
            message = msg + 'You lose!'
            game.history.append(message)
            game.put()
            game.end_game(game=request.urlsafe_game_key, message=message,
                          player_hand=player_hand, computer_hand=computer_hand,
                          won=False)
            return game.to_form(message)
        elif result == 'Tie':
            message = msg + 'Tie! You can\'t beat me. I am challenging you!'
            game.history.append(message)
            game.put()
            game.end_game(game=request.urlsafe_game_key, message=message,
                          player_hand=player_hand, computer_hand=computer_hand,
                          won=False)
            return game.to_form(message)
示例#29
0
    def _createSessionObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        # load necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = _getUserId()

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # get and check conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check to see if that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user is the owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add sessions.')

        # copy SessionForm/ProtoRPC Message into a dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        # convert dates from strings to Dates
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        # convert time from strings to Times
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        # make key based off of relationship
        p_key = ndb.Key(Conference, conf.key.id())
        c_id = Session.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Session, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = user_id
        del data['websafeConferenceKey']
        del data['websafeKey']

        Session(**data).put()

        # check if speaker exists in other sections if the do, add to memcache

        taskqueue.add(params={'speaker': data['speaker']},
                      url='/tasks/set_featured_speaker')

        # send request over to form.
        return self._copySessionToForm(request)
示例#30
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # get 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 create a conference's session.")

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeConferenceKey']

        # add default values for those missing (both data model & outbound Message)
        for df in SESS_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESS_DEFAULTS[df]
                setattr(request, df, SESS_DEFAULTS[df])

        # convert dates from strings to Date objects
        if data['sessionDate']:
            data['sessionDate'] = datetime.strptime(data['sessionDate'][:10],
                                                    "%Y-%m-%d").date()

        # generate Conference Key based on conference ID and Session
        # ID based on Conference key get Session key from ID
        c_key = conf.key
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key
        #data['conferenceId'] = conf.key.id()

        # create Session
        Session(**data).put()
        taskqueue.add(params={
            'speaker': data['speaker'],
            'websafeConferenceKey': request.websafeConferenceKey
        },
                      url='/tasks/set_featured_speaker')
        return self._copySessionToForm(s_key.get())