Exemplo n.º 1
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("The session must belong to a valid conference.")

        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf = c_key.get()

        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException(
                "Only the conference organizer can\
                 create sessions in this conference."
            )

        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data["websafeConferenceKey"]
        del data["websafeKey"]

        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
        Session(**data).put()

        return self._copySessionToForm(s_key.get())
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        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")

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

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

        # Getting a TEMP conference key for the moment
        q = Conference.query()
        cons = q.get()
        c_key = cons.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

        Session(**data).put()

        return request
Exemplo n.º 3
0
    def _createSessionObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # copy request's fields to dictionary
        data = {field.name: getattr(request, field.name) for field in
                request.all_fields()}

        # convert date and time strings to corresponding data types
        data['date'] = datetime.strptime(data['date'], '%Y-%m-%d').date()
        data['time'] = datetime.strptime(data['time'], '%H:%M').time()

        c_key = ndb.Key(urlsafe=data['websafeConferenceKey'])
        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

        # delete extraneous fields
        del data['websafeConferenceKey']
        del data['websafeSessionKey']

        # create Session object based on dictionary data and insert
        Session(**data).put()

        # set featured speaker
        taskqueue.add(params={'speaker': request.speaker},
                      url='/tasks/set_featured_speaker')

        return request
 def _createSessionObject(self, request):
     """Create Session Object, returning SessionForm/request"""
     user = endpoints.get_current_user()
     user_id = getUserId(user)
     #copy Session/ProtoRPC Message into dict
     data = {field.name: getattr(request, field.name) for field in request.all_fields()}
     
     #copy the websafe key 
     conf_key = request.confwebsafeKey
     data['confwebsafeKey'] = conf_key
     
     #change the date to Date format
     if data['date']:
         data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
     if data['startTime']:
         data['startTime'] = datetime.strptime(data['startTime'],"%H:%M").time()
     if data['duration']:
         data['duration'] = float(data['duration'])
     
     #generating session key by the Conference
     c_key = ndb.Key(urlsafe=request.confwebsafeKey)
     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
     del data['sess_key']
     #create session.. now 
     Session(**data).put()
     
     
     taskqueue.add(params={'speaker': data['speaker'], 'confwebsafeKey': conf_key},
     url='/tasks/set_featured_speaker',
     method = 'GET')
         
     return self._copySessionToForm(request)
Exemplo n.º 5
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)

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

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

        # generate Conference Key based on conference ID and Session
        # ID based on Profile key get Conference key from ID
        c_key = ndb.Key(Conference, request.websafeConferenceKey)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)

        # copy SessionForm/ProtoRPC Message into dict
        sf = SessionForm()
        data = {}
        data['key'] = s_key
        setattr(sf, 'sessionKey', s_key.urlsafe())
        for field in sf.all_fields():
            if hasattr(request, field.name):
                attribute = getattr(request, field.name)
                if field.name == 'date':
                    try:
                        datetime.strptime(attribute, "%Y-%m-%d")
                    except:
                        raise BadRequestException(
                            "Session 'date' format is 'yyyy-mm-dd'")
                elif field.name == 'startTime':
                    try:
                        datetime.strptime(attribute, "%H:%M")
                    except:
                        raise BadRequestException(
                            "Session 'startTime' format is 'hh:mm' (24-hour clock)")

                setattr(sf, field.name, attribute)
                data[field.name] = attribute

        del data["sessionKey"]
        Session(**data).put()

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

        return sf
    def _createSpeakerObject(self, request):
        """Create a Speaker object, returning SpeakerForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # Confirm the field is filled out
        checkField(request.name, 'name')

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

        # Create a key for the Speaker
        s_id  = Session.allocate_ids(size=1)[0]
        s_key = ndb.Key(Speaker, s_id)
        
        # Update stored session with session keys
        data['key'] = s_key
        
        # Create and update session and return the form
        Speaker(**data).put()
        
        taskqueue.add(
        
            params = {
                'email'   : user.email(),
                'subject' : 'You Added %s as a Speaker!' % data['name'],
                'body'    : 'Here are the details for the added speaker:',
                'info'    : repr(request)},
        
            url    = '/tasks/send_confirmation_email')
        
        return request
Exemplo n.º 7
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
    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")

        # 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 dates/times from strings to Date/Time objects;
        if data['duration']:
            data['duration'] = datetime.strptime(data['duration'][:5], "%H:%M").time()
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        if data['start']:
            data['start'] = datetime.strptime(data['start'][:5], "%H:%M").time()

        # generate Profile Key based on user ID and Session
        # ID based on Profile key get Session key from ID
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # creation of Session & return (modified) SessionForm
        Session(**data).put()

        return self._copySessionToForm(request)
Exemplo n.º 9
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")

        # 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
Exemplo n.º 10
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())
Exemplo n.º 11
0
    def parseSession(self, request):
        """Parse a request into a Session and return it"""
        # preload necessary data items
        conferenceKey = request.websafeConferenceKey
        conference = ndb.Key(urlsafe=conferenceKey).get()

        if not conference:
            raise endpoints.BadRequestException("Conference does not exist")

        # 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']
        # add default values for those missing (both data model & outbound Message)
        for sessionDefault in SESSION_DEFAULTS:
            if data[sessionDefault] in (None, []):
                data[sessionDefault] = SESSION_DEFAULTS[sessionDefault]
                setattr(request, sessionDefault, SESSION_DEFAULTS[sessionDefault])

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

        if data['time']:
            data['time'] = datetime.strptime(data['time'][:5], "%H:%M").time()

        # generate a session ID based on the parent conference
        sessionId = Session.allocate_ids(size=1, parent=conference.key)[0]
        # create a session key
        sessionKey = ndb.Key(Session, sessionId, parent=conference.key)
        data['key'] = sessionKey
        data['conferenceId'] = conference.key.id()
        
        session = Session(**data)
        return session
Exemplo n.º 12
0
 def _createSpeakerObject(self, request):
     """Create a Speaker object, returning SpeakerForm/request."""
     # Ensure that the current user is logged in and get user ID
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     # Verify that a name was provided for the speaker
     if not request.name:
         raise endpoints.BadRequestException(
             "Speaker 'name' field required")
     # Copy SpeakerForm/ProtoRPC Message into dict
     data = ({
         field.name: getattr(request, field.name)
         for field in request.all_fields()
     })
     # Create a key for the Speaker
     s_id = Session.allocate_ids(size=1)[0]
     s_key = ndb.Key(Speaker, s_id)
     # Update stored session with session keys
     data['key'] = s_key
     # create Session, send email to organizer confirming
     # creation of Session & return (modified) SessionForm
     Speaker(**data).put()
     taskqueue.add(params={
         'email': user.email(),
         'subject': 'You Added %s as a Speaker!' % data['name'],
         'body': 'Here are the details for the added speaker:',
         'info': repr(request)
     },
                   url='/tasks/send_confirmation_email')
     return request
Exemplo n.º 13
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
Exemplo n.º 14
0
    def _createSessionObject(self, request):
        """Create Session object, return SessionForm/request."""
        user = endpoints.get_current_user()
        # check if logged on user - error if not
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # ensure session has a name (name is a required field)
        # return error if not
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required (createSessionObject)")
        # assign websafe conference key to variable to pass to task queue
        wsck = request.websafeConferenceKey
        # get the conference and conference key
        conf = ndb.Key(urlsafe=wsck).get()
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)

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

        # 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])
        # assign data with to form to pass back
        sf = SessionForm(**data)

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

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'], "%H:%M").time()
        # test that the current user is authorized to create sessions for this conference
        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException("Only the conference creator can add sessions.")

        # create session id and session 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

        # create Session
        Session(**data).put()
        # use queue to determine featured speaker
        # sessions = Session.query(ancestor=c_key)

        # push task to determine conference featured speaker
        # pass this sessions speaker and conferences websafeConference key
        # to handler DetermineFeaturedSpeakerHandler in main.py
        taskqueue.add(params={'speaker': data['speaker'],
            'wsck': wsck},
            url='/tasks/determine_feature_speaker',method='GET'
        )
        # return (modified) SessionForm
        return sf
    def _createSessionObject(self, request):
        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")

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # Check that user trying to Create the Session is the Owner of the Conference.
        if conf.organizerUserId != user_id:
            raise endpoints.BadRequestException(
                "You must be the Owner of the Conference to Create a Session")

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


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

        # make Parent Key from Conference ID
        parent_key = ndb.Key(Conference, conf.key.id())

        # allocate new Session ID with Conference key as parent
        s_id = Session.allocate_ids(size=1, parent=parent_key)[0]

        # make Session key from ID
        s_key = ndb.Key(Session, s_id, parent=parent_key)
        data['key'] = s_key


        # Check to see if the Speakers email already present in Datastore, 
        # Then adds this Session key to Speakers list of Sessions to Speak at.
        if  data['speakersEmail']:
            oneSpeaker = Speaker.query(Speaker.mainEmail == data['speakersEmail'])
            oneSpeaker = oneSpeaker.get()
            oneSpeaker.sessionsToSpeak.append(s_key.urlsafe())
            oneSpeaker.put()
        del data['speakersEmail']


        Session(**data).put()

        # Check if there is a speaker, if so run the featuredspeaker task.
        if data['speaker']:
            taskqueue.add(
                params={
                    'websafeConferenceKey': request.websafeConferenceKey,
                    'speaker': data['speaker']},
                method='GET',
                url='/tasks/featuredSpeaker')
        return request
    def _createSessionObject(self, request):
        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")

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # Check that user trying to Create the Session is the Owner of the Conference.
        if conf.organizerUserId != user_id:
            raise endpoints.BadRequestException(
                "You must be the Owner of the Conference to Create a Session")

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

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

        # make Parent Key from Conference ID
        parent_key = ndb.Key(Conference, conf.key.id())

        # allocate new Session ID with Conference key as parent
        s_id = Session.allocate_ids(size=1, parent=parent_key)[0]

        # make Session key from ID
        s_key = ndb.Key(Session, s_id, parent=parent_key)
        data['key'] = s_key

        # Check to see if the Speakers email already present in Datastore,
        # Then adds this Session key to Speakers list of Sessions to Speak at.
        if data['speakersEmail']:
            oneSpeaker = Speaker.query(
                Speaker.mainEmail == data['speakersEmail'])
            oneSpeaker = oneSpeaker.get()
            oneSpeaker.sessionsToSpeak.append(s_key.urlsafe())
            oneSpeaker.put()
        del data['speakersEmail']

        Session(**data).put()

        # Check if there is a speaker, if so run the featuredspeaker task.
        if data['speaker']:
            taskqueue.add(params={
                'websafeConferenceKey': request.websafeConferenceKey,
                'speaker': data['speaker']
            },
                          method='GET',
                          url='/tasks/featuredSpeaker')
        return request
Exemplo n.º 17
0
 def _createSpeakerObject(self, request):
     """Create a Speaker object, returning SpeakerForm/request."""
     # Ensure that the current user is logged in and get user ID
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     # Verify that a name was provided for the speaker
     if not request.name:
         raise endpoints.BadRequestException(
             "Speaker 'name' field required")
     # Copy SpeakerForm/ProtoRPC Message into dict
     data = ({field.name: getattr(request, field.name)
             for field in request.all_fields()})
     # Create a key for the Speaker
     s_id  = Session.allocate_ids(size=1)[0]
     s_key = ndb.Key(Speaker, s_id)
     # Update stored session with session keys
     data['key'] = s_key
     # create Session, send email to organizer confirming
     # creation of Session & return (modified) SessionForm
     Speaker(**data).put()
     taskqueue.add(
         params = {
             'email'   : user.email(),
             'subject' : 'You Added %s as a Speaker!' % data['name'],
             'body'    : 'Here are the details for the added speaker:',
             'info'    : repr(request)},
         url    = '/tasks/send_confirmation_email')
     return request
Exemplo n.º 18
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)
    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('Sesssion "name" field required')

        if not request.speaker:
            raise endpoints.BadRequestException('Speaker field is required')

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

        # check that user is organizer
        if user_id != conference.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the organizer can 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()

        # generate parent (Conference) Key
        parent_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        # allocate new child (Sesssion) ID with parent_key as parent
        child_id = Session.allocate_ids(size=1, parent=parent_key)[0]
        # make child Key from ID
        child_key = ndb.Key(Session, child_id, parent=parent_key)
        data['key'] = child_key
        data['organizerUserId'] = user_id
        del data['websafeConferenceKey']
        del data['websafeKey']

        Session(**data).put()

        # Add Task queue. Query for Sessions for speaker and ancestory
        # key will be done on the Task rather than here
        taskqueue.add(
            params={'speaker': data['speaker'],
            'parentKey': str(parent_key.urlsafe())
            },
            url='/tasks/add_featured_speaker_to_memcache'
        )

        return request
Exemplo n.º 20
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Check if user is authorized
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

        # Check if required Form fields have been filled
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        # Retrieve the conference Key and check if it exists
        websck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=websck).get()
        if not conf:
            raise endpoints.NotFoundException("No conference found with key: %s" % websck)

        # Check that user is owner of conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException("Only the owner can update the conference.")

        # Copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        sess = self._copySessionToForm(request)
        del data["websafeConferenceKey"]
        del data["websafeSessionKey"]

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

        # Convert dates and times from strings to Date and Time objects; set month based on start_date
        if data["date"]:
            data["date"] = datetime.strptime(data["date"][:10], "%Y-%m-%d").date()

        if data["duration"]:
            data["duration"] = datetime.strptime(data["duration"][:5], "%H:%M").time()

        if data["startTime"]:
            data["startTime"] = datetime.strptime(data["startTime"][:5], "%H:%M").time()

        # Generate Session Key from obtained Conference key
        s_id = Session.allocate_ids(size=1, parent=ndb.Key(urlsafe=request.websafeConferenceKey))[0]
        s_key = ndb.Key(Session, s_id, parent=ndb.Key(urlsafe=request.websafeConferenceKey))
        data["key"] = s_key

        # Create Session
        Session(**data).put()

        # Add to task queue parameters needed to determine featured speaker
        taskqueue.add(
            params={"speaker": data["speaker"], "websafeConferenceKey": websck}, url="/tasks/determine_featured_speaker"
        )

        # Return (modified) SessionForm
        return sess
Exemplo n.º 21
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())
Exemplo n.º 22
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Get current user.
        user = endpoints.get_current_user()
        # If there isn't one, raise an authorization exception.
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # Set user id using getUserId
        user_id = getUserId(user)
        # Make sure a name is present
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
        # Make sure websafeConferenceKey is present
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("Session 'websafeConferenceKey' field required")
        # Get websafeConferenceKey
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # Check 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.')
        # 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']
        del data['conferenceName']

        # Add default values for those missing
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

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

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()

        # Generate keys for Session.
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # creation of Session & return (modified) SessionForm
        Session(**data).put()

        sessions = Session.query(Session.speaker == data['speaker']).count()
        if sessions > 1:
            taskqueue.add(params={'speaker': data['speaker']}, url='/tasks/set_featured_speaker')

        # send request over to form.
        return self._copySessionToForm(request)
Exemplo n.º 23
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
Exemplo n.º 24
0
    def _createSessionObject(self, request):
        """Create Session Object, w/ createSession method returns the request ."""
        #get the current user logged in
        user = endpoints.get_current_user()
        #if there is not a user logged in currently
        if not user:
        	#advise auth is requried to proceed
            raise endpoints.UnauthorizedException('User Authorization required')
        #-----user exists--------
        #get user id from user object
        user_id = getUserId(user)
        #if the name field has not been filled 
        if not request.name:
            raise endpoints.BadRequestException("The session field 'name' is required")
        #if the websafe conference field has not been filled
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("The session field 'websafeConferenceKey' is required")
        #get the conference assosiated with the provided websafeconferencekey
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        #if the conference is not found given the provided websafeconferencekey 
        if not conf:
            raise endpoints.NotFoundException(
                "A conference could not be found with the conference key: %s" % request.websafeConferenceKey)
        #if the user who is logged in is not the origional creater of the conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                "The maker of the conference is the only one that can update it.")
        #get the field data from the request
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeKey']
        del data['websafeConferenceKey']
        del data['conferenceName']

        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])
        #if the session has a date format it.
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        #if the session has a start time format it. 
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()

        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        Session(**data).put()
        #get the number of speakers 
        #sessions = Session.query(Session.speaker == data['speaker']).count()
        #if there is more than one speaker set the featured
        
        #if sessions > 1:
        taskqueue.add(params={'speaker': data['speaker'], 'websafeConferencekey': c_key}, url='/tasks/set_featured_speaker')

        #return self._copySessionToForm(request)
        return self._copySessionToForm(s_key.get())
Exemplo n.º 25
0
    def _createSessionObject(self, request):
        """Create or update a 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")

        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("Session 'conference key' field required")

        # 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']

        # retrieve parent conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # if current user is not the Conference creator, raise an exception
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can create sessions on the conference.')
        
        # convert dates from strings to Date objects
        if data['date']:
            try:
                data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
            except ValueError as e:
                raise endpoints.BadRequestException(str(e)) 

        if data['startTime']:
            try:
                data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()
            except ValueError as e:
                raise endpoints.BadRequestException(str(e)) 

        # Adjust session type enum field
        if data['typeOfSession']:
            data['typeOfSession'] = str(data['typeOfSession'])
        else:
            data['typeOfSession'] = 'NOT_SPECIFIED'

        # use the Conference websafe key as parent key for the session
        p_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # create Session, check if speaker should be featured
        Session(**data).put()
        taskqueue.add(params={'speaker': data['speaker'],
            'conferenceKey': request.websafeConferenceKey},
            url='/tasks/set_featured_speaker'
        )
        return BooleanMessage(data=True)
Exemplo n.º 26
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        
        # verify if the user is authorized
        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")

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

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

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

        # convert date from string 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 user ID and Conference
        # ID based on Conference key get Conference 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
        del data['websafeConferenceKey']
        del data['websafeKey']

        # create Session, send email to organizer confirming
        # creation of Session & return (modified) SessionForm
        Session(**data).put()
        
        # Broadcast a featured speaker through a memcache
        sessions = Session.query(Session.speaker == data['speaker'], ancestor=p_key)
        if len(list(sessions)) > 1:
            cache_data = {}
            cache_data['speaker'] = data['speaker']
            cache_data['sessionNames'] = [session.name for session in sessions]
            if not memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY, cache_data):
                logging.error('Memcache set failed.')
                
        return request
Exemplo n.º 27
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)
Exemplo n.º 28
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""

        # get Conference object from request; bail if not found
        # TODO: change this check to a try-except block
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.websafeConferenceKey)

        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Verify that the user_id belongs to conference organizer group
        if not user_id == conf.organizerUserId:
            raise endpoints.UnauthorizedException('Only organizer can create session')

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

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

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

        try:
            data['startTime'] = datetime.strptime(data['startTime'][:10], "%H:%M").time()
        except ValueError:
            raise endpoints.BadRequestException("Make sure that your start time is in HH:MM format")

        # generate Session key with Conference key as parent
        p_key = conf.key
        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

        self._createSessionSpeakerObject(data['speakerName'], data['speakerEmail'])
        del data['speakerName']
        del data['websafeConferenceKey']
        del data['websafeSessionKey']

        # create Session, send email to organizer confirming
        # creation of Session & return (modified) SessionForm
        Session(**data).put()
        taskqueue.add(params={'websafeConfKey': request.websafeConferenceKey,
            'speakerEmail': data['speakerEmail']},
            url='/tasks/featured_speaker'
        )
        taskqueue.add(params={'email': user.email(),
            'sessionInfo': repr(request)},
            url='/tasks/send_confirmation_email'
        )
        return request
Exemplo n.º 29
0
    def _createSessionObject(self, request):
        """Create Session object for a conference, given the conference key."""
        # is the user signed in?
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get Conference object from passed in websafeConferenceKey
        conf_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conference = conf_key.get()

        # validate conference, user, and session name
        if not conference:
            raise endpoints.NotFoundException(
                'Invalid conference key: %s' % request.websafeConferenceKey) 
        if user_id != conference.organizerUserId:
            raise endpoints.BadRequestException(
                'User must be the conference organizer to add a new session.')
        if not request.name:
            raise endpoints.BadRequestException(
                'Session name is required.')

        # copy SessionForm message into a dictionary and process it
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeConferenceKey']
        del data['websafeKey']

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

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

        # use sessionType enum field's name string value
        if data['sessionType']:
            data['sessionType'] = data['sessionType'].name

        # create new id and key for session with conf_key as parent
        session_id = Session.allocate_ids(size=1, parent=conf_key)[0]
        session_key = ndb.Key(Session, session_id, parent=conf_key)
        data['key'] = session_key

        # put Session in data store
        Session(**data).put()

        # add a new task to find feature speaker
        taskqueue.add(
            params={'session': str(session_key.urlsafe())},
            url='/tasks/set_featuredSpeaker'
        )

        # return SessionForm object
        return self._copySessionToForm(session_key.get())
Exemplo n.º 30
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning ConferenceForm/request."""
        # get user id 
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # check to make sure required fields are present
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
        if not request.conferenceId:
            raise endpoints.BadRequestException("Session 'conferenceId' field required")

        # check to make sure given conference is an actual conference
        conference_key = ndb.Key(urlsafe=request.conferenceId)
        if not conference_key:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.conferenceId)

        # check to make sure user is owner of this conference
        conference = conference_key.get()
        if user_id != conference.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

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

        # add default values for those missing (both data model & outbound Message)
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
        # convert dates from strings to DateTime objects
        if data['dateTime']:
            data['dateTime'] = datetime.strptime(data['dateTime'][:16], "%Y-%m-%dT%H:%M")

        # set seatsAvailable to be same as maxAttendees on creation
        # it defaults to 0 if not provided in request
        data["seatsAvailable"] = data["maxAttendees"]

        # generate Session Key based on conference ID and Session

        session_id = Session.allocate_ids(size=1, parent=conference_key)[0]
        session_key = ndb.Key(Session, session_id, parent=conference_key)
        data['key'] = session_key

        # create Session & return (modified) ConferenceForm
        newSession = Session(**data)
        newSession.put()

        # if speaker given, schedule Task to check for Featured Speaker
        if data['speakerUserId']:
            taskqueue.add(params={'websafeConferenceKey': conference_key.urlsafe(),
                'speakerUserId': data['speakerUserId']},
                url='/tasks/check_featured_speaker'
            )

        return self._copySessionToForm(newSession)
    def _createSessionObject(self, request, user=None):
        """Create Session object, returning SessionForm/request."""
        user_id = getUserId(user)
        # get Conference object from request; bail if not found
        wck = request.websafeConferenceKey
        c_key = ndb.Key(urlsafe=wck)
        conf = c_key.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wck)

        # Check editing authorization. Creater and user match
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only conference creator may add sessions')

        if not request.name or not request.date or not request.startTime:
            raise endpoints.BadRequestException(
                "Session 'name', 'date', and 'startTime' fields required")

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

        # convert date/time strings to Date/Time objects
        if data['date']:
            data['date'] = datetime.strptime(
                                data['date'][:10], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(
                                    data['startTime'][:10], "%H:%M").time()

        # Check date is within conference date range (if specified)
        if conf.startDate and conf.endDate:
            if data['date'] < conf.startDate or data['date'] > conf.endDate:
                raise endpoints.BadRequestException(
                    "Session date is not within conference timeframe.")

        # generate Session Key based on parent 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

        # create Session & return (modified) SessionForm
        sess = Session(**data)
        sess.put()

        # Send speaker names to taskqueue for processing featured speaker
        for speaker in data['speaker']:
            taskqueue.add(
                url='/tasks/set_featured_speaker',
                params={'speaker': speaker, 'websafeConferenceKey': wck}
            )

        return self._copySessionToForm(sess)
    def _createSessionObject(self, request):
        """Create or update _createSessionObject object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        #check if authorized
        user_id = getUserId(user)
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException('Incorrect Authorization')

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

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

        if not data['typeOfSession']:
            data['typeOfSession'] = str(SessionType.NOT_SPECIFIED)
        else: 
            data['typeOfSession']= str(data['typeOfSession'])

        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

        # convert dates from strings to Date objects; set month based on start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        else:
            data['date'] = datetime.now()

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'], '%I:%M%p').time()
        else:
            data['startTime'] = datetime.strptime('12:00AM', '%I:%M%p').time()
            
        # generate session Key/ID based on conference key
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        #create session
        Session(**data).put()

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

        print s_key.get();
        return self._copySessionToForm(s_key.get())
Exemplo n.º 33
0
	def _createSessionObject(self, request):
		"""Create 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)
		
		
		# get the conference object user is trying to add a session to
		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 the owner
		if user_id != conf.organizerUserId:
			raise endpoints.ForbiddenException(
				'Only the owner can update the conference.')

		
		if not request.name:
			raise endpoints.BadRequestException("Session 'name' field required")
		
		
		# copy SessionForm/ProtoRPC Message into dict
		data = {field.name: getattr(request, field.name) for field in request.all_fields()}


		# convert dates and times from strings to date/time objects
		if data['date']:
			data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
		if data['startTime']:
			data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()
			

		# create session key with ancestor relationship 
		conf_key = conf.key
		session_id = Session.allocate_ids(size=1, parent=conf_key)[0]
		session_key = ndb.Key(Session, session_id, parent=conf_key)
		data['key'] = session_key
		data['websafeSessionKey'] = session_key.urlsafe()
		
		
		# create Session
		Session(**data).put()
		
		
		# if speaker is defined, check if they qualify as Featured Speaker
		if data['speaker']:
			taskqueue.add(params={'speaker': data['speaker'],
				'websafeConferenceKey': request.websafeConferenceKey},
				url='/getFeaturedSpeaker')
		

		return request
Exemplo n.º 34
0
    def _createSessionObject(self, request):
        """ Create Session Object
        
        If a speaker is specified, check validity and add his key to the session
        """
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

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

        del data["websafeKey"]

        conf_key = ndb.Key(urlsafe=wsck)
        conf = conf_key.get()
        # check that conference exists
        if not conf or conf_key.kind() != "Conference":
            raise endpoints.NotFoundException("No conference found with key: %s" % wsck)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException("Only the owner can update the conference.")
        # Create the Session Object from Input
        # 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 and Time objects respectively
        if data["date"]:
            data["date"] = datetime.strptime(data["date"][:10], "%Y-%m-%d").date()
        if data["startTime"]:
            data["startTime"] = datetime.strptime(data["startTime"][:5], "%H:%M").time()

        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

        # check if speaker is provided and exists
        if data["speaker"]:
            speaker = self._getSpeaker(data["speaker"])
            data["speaker"] = speaker.key
            # abort if no speaker
            if not speaker:
                raise endpoints.NotFoundException("No speaker found with key: %s" % data["speaker"])

            # add the task for featured speaker
            taskqueue.add(params={"wsck": wsck, "speaker": speaker.fullName}, url="/tasks/featured_speaker")

        del data["websafeConferenceKey"]
        Session(**data).put()

        return self._copySessionToForm(request)
Exemplo n.º 35
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")

        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("Conference 'websafeConferenceKey' field required")

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

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException("Only the conference owner can create 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']
        del data['conferenceName']

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

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

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()


        # generate Session Key
        # ID based on Profile key get Conference key from ID
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # creation of Session & return SessionForm
        Session(**data).put()

        # add a new Memcache entry that features the speaker and session names
        # if the speaker has more than one session at this conference
        taskqueue.add(params={'speaker': data['speaker'],
                              'c_key': request.websafeConferenceKey},
                              url='/tasks/set_featured_speaker')

        return self._copySessionToForm(request)
Exemplo n.º 36
0
    def createSession(self, request):
        """Create session in the conference identified by websafeConferenceKey."""
        # Get Conference object from request and raise exception if not found
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.websafeConferenceKey)

        if not isinstance(conf, Conference):
            raise endpoints.BadRequestException('Key must refer to Conference')

        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if user_id != conf.organizerUserId:
            raise endpoints.UnauthorizedException("Only the user who created the conference can add sessions")

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

        if not request.speaker:
            raise endpoints.BadRequestException("Session 'speaker' is a required field")


        # Copying SessionForm/ProtoRPC Message into dictionary
        # getattr is required to access the values
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeConferenceKey']
        del data['websafeKey']

        # Parsing date strings to get Date objects
        # The month is set based on start date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        else:
            data['date'] = conf.startDate

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()


        data['typeOfSession'] = str(data['typeOfSession'])


        s_id = Session.allocate_ids(size=1, parent=conf.key)[0]
        s_key = ndb.Key(Session, s_id, parent=conf.key)
        data['key'] = s_key
        session = Session(**data)
        session.put()
        taskqueue.add(params={'speaker': data['speaker'],
                    'wcsk': request.websafeConferenceKey},
                    url='/tasks/set_feature_session_announcement'
                )
        return self._copySessionToForm(session)
Exemplo n.º 37
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")

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

        if conf.organizerUserId != user_id:
            raise endpoints.BadRequestException("Sessions can only be created by the conference organizer.")

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

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

        type_list = ["NOT_SPECIFIED", "Workshop", "Lecture", "Demo", "Seminar", "Debate", "Panel"]
        # convert dates from strings to Date objects; set month based on start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:10], "%H:%M").time()
        if data['typeOfSession']:
            if data['typeOfSession'] not in type_list:
                raise endpoints.BadRequestException(type_of_session_error)
        if data['speaker']:
            speaker = data['speaker']
        # generate conference Key based on websafeconferencekey from request, c_key = websafeConferenceKey might work?
        # ID based on conference key, get session key from ID
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # create Session, send speaker info to task queue for featured speaker announcement
        # creation of Session & return (modified) SessionForm
        Session(**data).put()
        if speaker:
            taskqueue.add(params={'speaker': speaker, 'conference_key': request.websafeConferenceKey},
                url='/tasks/featured_speaker'
            )
        sess = s_key.get()
        return self._copySessionToForm(sess)
    def _createSessionObject(self, request):
        """Create or update Conference 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 cinference key
        wsck = request.websafeConferenceKey
        # get conference object
        c_key = ndb.Key(urlsafe=wsck)
        conf = c_key.get()
        # check that conference exists or not
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)
        # check that user is owner
        if conf.organizerUserId != getUserId(endpoints.get_current_user()):
            raise endpoints.ForbiddenException(
                'You must be the organizer to create a session.')

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        # convert date and time from strings to Date objects; 
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:10],  "%H, %M").time()
        # allocate new Session ID with Conference key as parent
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        # make Session key from ID
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key
        data['websafeConferenceKey'] = wsck
        del data['sessionSafeKey']

        #  save session into database
        Session(**data).put()
        # This task wil send a confirmation email to the owner 
        taskqueue.add(params={'email': user.email(),
            'conferenceInfo': repr(request)},
            url='/tasks/send_confirmation_session_email'
        )
        speaker = data['speaker']
        taskqueue.add(
            url='/tasks/check_featured_speaker',
            params={'speaker': speaker, 'websafeConferenceKey': wsck}
        )
        return request
Exemplo n.º 39
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")

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

        # 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; set month based on Date
        if data['Date']:
            data['Date'] = datetime.datetime.strptime(data['Date'][:10],
                                                      "%Y-%m-%d").date()

        # generate key from websafeConferenceKey
        p_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        # allocate new Session ID with Conference key as parent
        c_id = Session.allocate_ids(size=1, parent=p_key)[0]
        # make Session key from ID
        my_key = ndb.Key(Session, c_id, parent=p_key)

        data['key'] = my_key

        # create Conference & return (modified) ConferenceForm
        Session(**data).put()

        #Check if theres more session for this speaker.
        featuredSpeaker = Session.query(Session.speaker == data['speaker'])
        sessions = [session.name for session in featuredSpeaker]
        if sessions:
            featureText = data['speaker'] + ': ' + ', '.join(sessions)
            #Set in memcache
            memcache.set(MEMCACHE_FEATURED_KEY, featureText)

        # return sessionform
        return self._copySessionToForm(my_key.get())
Exemplo n.º 40
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Name is a required Field
        if not request.name:
            raise endpoints.BadRequestException(
                "Conference 'name' field required")

        # copy SessionForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        logging.info('All fields are in the data dictionary')

        query = Conference.query(
            Conference._properties['name'] == request.conferenceName).get()
        if not query:
            raise endpoints.NotFoundException(
                "No conference found with this name: %s", data['name'])
        conference = query
        logging.info('Found conference to add Session to = %s',
                     conference.name)
        logging.info('Websafe conference key is %s', conference.key.urlsafe())

        #  Put websafe key to the Session, has a relationship with the Conference
        data['conferenceKey'] = conference.key.urlsafe()

        # conferenceName is not in the Session object it was only needed to
        # find the Conference the Session belongs to so delet it and the rest
        # of unused fields
        del data['conferenceName']
        del data['displayName']

        # Insert default values for the session
        for df in SESSIONDEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSIONDEFAULTS[df]
                setattr(request, df, SESSIONDEFAULTS[df])

        session_id = Session.allocate_ids(size=1)[0]
        session_key = ndb.Key(Session, session_id)
        websafeKey = session_key.urlsafe()
        logging.info('The websafe key for this session is: %s', websafeKey)
        data['websafeKey'] = websafeKey

        conference.sessionKeys.append(websafeKey)

        # creation of Session & return (modified) SessionForm
        conference.put()
        Session(**data).put()

        return request
Exemplo n.º 41
0
    def _createSessionObject(self, request):
        """Create or update Session 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(
                "Conference 'name' field required")

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

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

        # convert dates from strings to Date objects; set month based on start_date

        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        if data['duration']:
            data['duration'] = datetime.strptime(data['duration'][:2],
                                                 "%H").time()

        # generate Profile Key based on user ID and Session
        # ID based on Profile key get Session key from ID
        p_key = ndb.Key(Profile, user_id)
        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

        # create Session
        Session(**data).put()

        return request
Exemplo n.º 42
0
    def _createSessionObject(self, request):
        """Create Session object, returning SessionForm"""
        # User authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)

        # User Authorization
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add session to the conference')

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

        # add default values for fields that aren't provided
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])
        if data['date']:
            data['date'] = datetime.strptime(
                                    data['date'][:10], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(
                                        data['startTime'], "%H:%M").time()

        # generate session Key based on conference Key
        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
        Session(**data).put()

        # Run queue to check featured speaker if speaker ID is provided
        if data['speakerId']:
            speaker = ndb.Key(Speaker, data['speakerId']).get()
            if not speaker:
                raise endpoints.NotFoundException(
                    'No speaker found with this id')
            taskqueue.add(params={'wsck': wsck, 'speakerId': data['speakerId']},
                          url='/tasks/check_featured_speaker'
                          )
        return self._copySessionToForm(s_key.get())
Exemplo n.º 43
0
    def _createSessionObject(self, request):
        """Create Session object, returning SessionForm/request."""
        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # copy SessionForm into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        user_id = getUserId(user)

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

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

        # add date and time
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'],
                                                  "%H:%M").time()
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        # generate session key from conference key
        conf = ndb.Key(urlsafe=data['confwebsafeKey']).get()
        p_key = conf.key
        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
        if not data['speaker']:
            data['speaker'] = user.nickname()
        del data['confwebsafeKey']

        # if speaker has at least 2 sessions, add speaker to featured speaker memcache
        # The idea for defining the featured speaker and some of the session and wishlist endpoints came from
        # app id:  weighty-gasket-91618, author unknown

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

        Session(**data).put()
        return request
    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")

        wsck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=wsck).get()

        if (user_id != conf.organizerUserId):
            raise endpoints.BadRequestException(
                "Not Organizer to create Session")

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

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

        if data['start_time']:
            data['start_time'] = datetime.strptime(data['start_time'][:10],
                                                   "%H:%M").time()

        # ID based on Conference key from ID
        c_key = conf.key
        c_sid = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, c_sid, parent=c_key)
        data['key'] = s_key
        data['conf_key'] = wsck

        Session(**data).put()

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

        return self._copySessionToForm(s_key.get())
Exemplo n.º 45
0
    def _createSessionObject(self, request):
        """Create Session object, returning SessionForm/request."""
        # check user, if no user, raise exception
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        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 create the session.')

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

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeSessionKey']
        del data['websafeConferenceKey']
        # add default values for those missing (both data model & outbound Message)
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

        # convert dates from strings to Date or time objects;
            if data['startDateTime']:
                temp = str(data['startDateTime'])
                data['startDateTime'] = datetime.strptime(temp, "%Y-%m-%d %H:%M:%S")
            else:
                # TODO debug code for query testing
                data['startDateTime'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # generate Profile Key based on user ID and Session
        # ID based on Profile key get Session key from ID
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # create Session, return (modified) SessionForm
        Session(**data).put()
        session = s_key.get()
        wssk = s_key.urlsafe()
        taskqueue.add(params={'sessionKey': wssk,
            'speaker': session.speaker},
            url='/tasks/set_speaker_announcement'
        )
        return self._copySessionToForm(session)
Exemplo n.º 46
0
    def createSessionObject(self, request):
        """Creat the session object"""
        #preload necessary data
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        user_id = getUserId(user)
        #check the user and errors
        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException(
                'Only Orgnizers can start sesssions')
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' required field")
        #constructing the data
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        print data['websafeKey']
        del data['websafeConferenceKey']
        del data['websafeKey']
        for df in DEFAULT_SESSION:
            if data[df] in (None, []):
                data[df] = DEFAULT_SESSION[df]
                setattr(request, df, DEFAULT_SESSION[df])
        #convert dates from strings to Date object
        if data['date']:
            data['date'] = datetime.strptime(data['date'], "%m-%d-%Y").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'],
                                                  "%H:%M:%S").time()
        data['confKey'] = request.websafeConferenceKey
        p_key = ndb.Key(Profile, user_id)
        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

        newSession = Session(**data)
        data['websafeKey'] = newSession.key.urlsafe()
        newSession.put()

        # This is for task 4: check whether the speaker is a featured speaker or not
        if data['speaker']:
            self.checkFeaturedSpeaker(data)

        return self._copySessionToForm(s_key.get())
Exemplo n.º 47
0
    def _createSessionObject(self, request):
        """Allows autheticated users to create a session for a conference"""
        # get user logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get conference of request
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check validity
        if not conf:
            raise endpoint.NotFoundException("Non-existing conference")

        # Check if user is organizer
        if user_id != getattr(conf, 'organizerUserId'):
            msg = 'Not organizer of conference'
            raise endpoints.UnauthorizedException(msg)

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

        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        # convert date from string to Date object
        if data['date']:
            dt = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
            data['date'] = dt
        # convert start time string to Time object
        if data['startTime']:
            st = datetime.strptime(data['startTime'][:10], "%H:%M").time()
            data['startTime'] = st

        conference_id = conf.key.id()
        c_key = ndb.Key(Conference, conference_id)
        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
        del data['websafeConferenceKey']
        del data['websafeKey']

        # create Session, enqueue check speaker task
        Session(**data).put()
        taskqueue.add(params={'speaker': data['speaker'],
                              'wsck': c_key.urlsafe()},
                      url='/tasks/check_speaker')
        return self._copySessionToForm(s_key.get())
Exemplo n.º 48
0
    def createSession(self, request):
        """Creating new sessions."""
        # # first check that user is conference creator
        wsck = request.websafeConferenceKey
        self._verifyConfCreator(wsck)

        # copy SessionForm/ProtoRPC Message into dict, omitting websafe key
        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 SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

        # convert date/time from strings to Datetime objects;
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        conf_key = ndb.Key(urlsafe=wsck)
        session_id = Session.allocate_ids(size=1, parent=conf_key)[0]
        session_key = ndb.Key(Session, session_id, parent=conf_key)
        data['key'] = session_key

        # check if session speaker has another session in this conference
        speaker_sesh = Session.query(Session.speaker == request.speaker,
                                     ancestor=conf_key).get()
        if speaker_sesh:
            # Yup, FEATURED SPEAKER! trigger task and end loop
            taskqueue.add(url='/tasks/set_featured_speaker',
                          params={
                              'websafeKey': wsck,
                              'speaker': request.speaker
                          })

        # create Session in datastore, passing in kwargs
        Session(**data).put()

        return request
Exemplo n.º 49
0
    def createSession(self, request):
        """Create Session object, returning SessionForm/request."""

        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

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

        c_key = ndb.Key(Conference, request.websafeConferenceKey)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)

        session = s_key.get()
        if not session:
            session = Session(
                key = s_key,
                name = request.name,
                speakerId = request.speakerId,
            )
            if request.highlights:
                session.highlights = request.highlights
            if request.duration:
                session.duration = request.duration
            if request.typeOfSession:
                session.typeOfSession = request.typeOfSession
            if request.date:
                session.date = datetime.strptime(request.date, "%Y-%m-%d").date()
            if request.startTime:
                session.startTime = datetime.strptime(request.startTime, "%H:%M:%S").time()
            session.put()

        taskqueue.add(params={'confKey': request.websafeConferenceKey, 'sessionKey': session.key.urlsafe(), 'speakerId': request.speakerId},
            url='/tasks/set_feature_speaker'
        )

        return self._copySessionToForm(session)
    def _sessionAdd(self, request):
        """Create a Session """
        prof = self._getProfileFromUser()  # get user Profile

        # check if conf exists given websafeConfKey
        # get conference; check that it exists
        wsck = request.websafeConferenceKey
        conf_k = ndb.Key(urlsafe=wsck)
        conf = conf_k.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)

        if prof.mainEmail != conf.organizerUserId:
            raise endpoints.NotFoundException(
                'Cannont create a sessions from this conference')
        # Check for valid time
        if 24 < request.startTime or 0 >= request.startTime:
            raise endpoints.NotFoundException(
                'Invalid time, Please use 24 hour format. e.g 17')
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeConferenceKey']

        if not data['typeOfSession']:
            data['typeOfSession'] = "NOT_SPECIFIED"
        else:
            data['typeOfSession'] = data['typeOfSession'].name
        # Allocates a range of key IDs for this model class.
        s_id = Session.allocate_ids(size=1, parent=conf_k)[0]
        # Create a Session key the includes session and parent info
        s_key = ndb.Key(Session, s_id, parent=conf_k)
        data['key'] = s_key
        session = Session(**data)
        s = session.put()
        # Added a task to check for feature speaker
        taskqueue.add(url='/tasks/set_Featured_Speaker',\
                      params={'key': wsck, 'speaker': data['speaker']})
        return self._copySessionToForm(s.get())
Exemplo n.º 51
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()

        p_key = ndb.Key(Conference, request.websafeConferenceKey)

        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
        del data['websafeConferenceKey']
        # create session and create task for assigning featured speaker to memcache
        Session(**data).put()
        if data['speaker']:
            taskqueue.add(url='/tasks/assign_featured_speaker', params={'speaker': data['speaker']})
        return self._copySessionToForm(request)    
Exemplo n.º 52
0
    def _createSessionObject(self, request):
        """ Create a new Session object, returning SessionForm/request. """
        # 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 owner can update the conference.")

        # check wether the "name" field is filled by user
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

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

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

        # convert sessionType from enum to string
        if data["typeOfSession"]:
            data["typeOfSession"] = str(data["typeOfSession"])

        # convert date from strings to Date objects
        if data["date"]:  # date
            data["date"] = datetime.strptime(data["date"][:10],
                                             "%Y-%m-%d").date()
            # check if the date is during the conference period
            conf_start_date = getattr(conf, "startDate")
            conf_end_date = getattr(conf, "endDate")
            if conf_start_date and conf_end_date:
                if data["date"] < conf_start_date or data[
                        "date"] > conf_end_date:
                    raise endpoints.BadRequestException("Invallid date")

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

        # compute the endTime using the duration field
        if data["duration"] and data["startTime"]:
            endTime_minute = (data["startTime"].minute + data["duration"]) % 60
            endTime_hour = data["startTime"].hour \
                      + (data["startTime"].minute + data["duration"]) / 60
            data["endTime"] = time(endTime_hour, endTime_minute)

        # delete unused fields
        del [data["duration"]]
        del [data["websafeConferenceKey"]]
        del [data["wssk"]]

        # make conference Key from the websafe conference key
        c_key = ndb.Key(urlsafe=wsck)

        # allocate new Session ID with the conference key as parent
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]

        # make Session key from ID
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data["key"] = s_key

        # creates the Session object and put onto the cloud datastore
        Session(**data).put()

        # add task to queue to update featured speaker
        taskqueue.add(params={"websafeConferenceKey": wsck},
                      url="/tasks/set_featured_speaker")

        # return the original Session Form
        return self._copySessionToForm(s_key.get())
Exemplo n.º 53
0
    def _createSessionObject(self, request):
        """Create a Session object, returning SessionForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # Check that the 'name' field if filed
        checkField(request.name, 'name')

        # Check that the 'parentKey' field if filed
        checkField(request.parentKey, 'parentKey')
        
        # Attempt to retrieve the Conference or raise an exception
        try:
            _key = ndb.Key(urlsafe=request.parentKey)
        except Exception:
            raise endpoints.BadRequestException(
                'The parentKey given is invalid.')
        
        # Retrieve the Conference Obj 
        conf = _key.get()
        
        # Verify that the current user created the conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the conference creator can add a session to it.')
        
        # Check speakerKey and save them
        speakers = []
        
        if request.speakerKey:
        
            for speakerKey in request.speakerKey:
        
                try:
                    speaker = ndb.Key(urlsafe=speakerKey).get()
                    speakers.append(speaker)
        
                except Exception:
                    raise endpoints.BadRequestException(
                        'Check the speakerKey it is invalid.')
        
        # Copy SessionForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})
        
        # If values not given for Session defaults, add defaults
        for df in SESSION_DEFAULTS:
        
            if data[df] in (None, []):
        
                data[df] = SESSION_DEFAULTS[df]
        
                setattr(request, df, SESSION_DEFAULTS[df])
        
        # Converting the date info from strings to Date objects
        # setting the object month to the start dates month
        if data['date']:
            data['date'] = (datetime.strptime(
                            data['date'][:10], "%Y-%m-%d").date())
            data['month'] = data['date'].month
        else:
            data['month'] = conf.month
        
        # Convert startTime from string to Time object
        if data['startTime']:
        
            data['startTime'] = (datetime.strptime(
                                 data['startTime'][:5], "%H:%M").time())
        
         # Convert typeOfSession to string
        if data['typeOfSession']:
        
            data['typeOfSession'] = str(data['typeOfSession'])
        
        # Create a session id for the Session,
        # create the relationship with parent key.
        s_id = Session.allocate_ids(size=1, parent=_key)[0]
        
        # Create the session key
        s_key = ndb.Key(Session, s_id, parent=_key)
        
        # Fill the session key
        data['key'] = s_key
        
        # Check that the speaker was passed
        if speakers:

            #  Query the session for instance of speakers 
            s = Session.query(
                ancestor=ndb.Key(urlsafe=request.parentKey))
            
            # Setting none as featured
            featured = None
            
            # Number of session
            instance_count = 0

            for spkr in data['speakerKey']:
                
                i_count = s.filter(Session.speakerKey == spkr).count()
                
                if i_count >= instance_count:
                
                    featured = spkr
                
                    minSessions = i_count

            # Advise of the featured Speaker using the taskQueue
            if featured:
                taskqueue.add(
                    params = {
                        'websafeConferenceKey': request.parentKey,
                        'websafeSpeakerKey'   : featured},
                    url    = '/tasks/set_featured_speaker',
                    method = 'GET')

        # Store in the DataStore
        Session(**data).put()
        
        # Send an email to the conference organizer
        taskqueue.add(
            params = {
                'email'   : user.email(),
                'subject' : 'You Created a New Session for %s!' % conf.name,
                'body'    : 'Here are the details for new Session:',
                'info'    : repr(request)},
            url    = '/tasks/send_confirmation_email')
        return request
    def _createSessionObject(self, request):
        """ Create or update Session object, returning SessionForm/request
        """
        # preload necesarry data items
        user = self.get_authed_user()
        user_id = getUserId(user)

        conf_wsk = request.websafeConferenceKey
        conf_key = ndb.Key(urlsafe=conf_wsk)
        conf = conf_key.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key {}'.format(
                    request.websafeConferenceKey))

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner of the conference may create a session.')

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

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

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

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

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

        data['typeOfSession'] = str(data['typeOfSession'])
        if data['speakers']:
            spkr_keys = [
                ndb.Key(urlsafe=speaker) for speaker in data['speakers']
            ]

            # Update session if there already is a websafeKey
            if data['websafeKey']:
                for speaker in spkr_keys:
                    self._updateSpeakerForSession(
                        websafeSpeakerKey=speaker.urlsafe(),
                        websafeSessionKey=data['websafeKey'],
                        add=True)
            data['speakers'] = spkr_keys

        # generate Conference Key based on websafeConferenceKey and
        # Session ID based on Conference Key and get Session websafe key
        # from ID.
        sess_id = Session.allocate_ids(size=1, parent=conf_key)[0]
        sess_key = ndb.Key(Session, sess_id, parent=conf_key)
        data['key'] = sess_key

        del data['websafeKey']
        del data['websafeConferenceKey']

        # create Session, send email to organizer confirming creation of
        # Session and return (modified) SessionForm
        session = Session(**data).put()

        # Check if there is more than one session by speakers of this
        # session. Speakers that are speaking at more than one session
        # of the same conference are featured speakers, and should be
        # added to a Memcache entry for featured speakers. (TASK 4)
        if data['speakers']:
            for speaker in data['speakers']:
                schedule = self._getSpeakerSchedule(speaker, conf_key)
                taskqueue.add(params={
                    'conf_wsk': conf_wsk,
                    'schedule': schedule
                },
                              url='/tasks/set_featured_speakers')

        taskqueue.add(params={
            'email': user.email(),
            'sessionInfo': repr(request)
        },
                      url='/tasks/send_confirmation_email')
        return self._copySessionToForm(session.get())
Exemplo n.º 55
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Get current user.
        user = endpoints.get_current_user()
        # If there isn't one, raise an authorization exception.
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # Set user id using getUserId
        user_id = getUserId(user)
        # Make sure a name is present
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")
        # Make sure websafeConferenceKey is present
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException(
                "Session 'websafeConferenceKey' field required")
        # Get websafeConferenceKey
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # Check 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.')
        # 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']
        del data['conferenceName']

        # Add default values for those missing
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

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

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        # Generate keys for Session.
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

        # creation of Session & return (modified) SessionForm
        Session(**data).put()

        sessions = Session.query(Session.speaker == data['speaker']).count()
        if sessions > 1:
            taskqueue.add(params={'speaker': data['speaker']},
                          url='/tasks/set_featured_speaker')

        # send request over to form.
        return self._copySessionToForm(request)