def addWishList(self, request):
        """Adds a session to a user wishlist"""
        user = endpoints.get_current_user()

        # User is logged in
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Check if parameters were provided
        if not request.websafeSessionKey:
            raise endpoints.BadRequestException('websafeSessionKey are required')

        # check that session exists
        session_key = ndb.Key(urlsafe=request.websafeSessionKey)
        session = session_key.get()
        if not session:
            raise endpoints.NotFoundException('No session found with key: %s' % request.websafeSessionKey)

        new_wishlist_session = UserWishList(
            userId=getUserId(user),
            websafeSessionKey=session_key.urlsafe()
        )
        new_wishlist_session.put()

        return UserWishListForm(
            userId=getUserId(user),
            websafeSessionKey=session_key.urlsafe()
        )
Example #2
0
File: app.py Project: snady/blag
def editprofile():
        error = ""
        userid = utils.getUserId(session['user'])
        profile = utils.getProfile(userid)
        if request.method == 'POST':
                if request.form['picsource'] != "" and request.form['age'] != "" and request.form['color'] != "":
                        utils.writeProfile(utils.getUserId(session['user']), request.form['picsource'], int(request.form['age']), request.form['color'])
                        return redirect(url_for('user', username=session['user']))
                else:
                        error = "Error: Missing fields"
                        return render_template("editprofile.html", error = error, profile = profile)
        else:
                return render_template("editprofile.html", error = error, profile = profile)
    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)
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")
        #Get conference key
        wsck = request.websafeConferenceKey
        #Get conference object
        c_key = ndb.Key(urlsafe = wsck)
        conf = c_key.get()
        #check if conf exist
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)
        #check if user is the creator of the conference
        if conf.organizerUserId != getUserId(endpoints.get_current_user()):
            raise endpoints.ForbiddenException(
                'You must be the organizer to create a session.')

        #copy Session/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_field()}
        #convert date and time from strings to Date objects;
        if data['date']:
            data['date'] = datetime.strptime(
                data['data'][:10], "%Y-%m-%d".date())
        if data['startTime']:
            datat['startTime'] = datetime.strptime(
                data['startTime'][:10], "%H,%M").time()
        # Allocate new Session ID with Conference key as the parent
        session_id = Session.allocate_ids(size = 1, parent = c_key)[0]
        # Make Session key from ID
        session_key = ndb.Key(Session, session_id, parent = c_key)
        data['key'] = session_key
        #Save session into database
        Session(**data).put()
        # Taskque for featuredSpeaker endpoint
        #check for featured speaker in conference:
        taskqueue.add(params={'speaker': data['speaker'],
                              'websafeConferenceKey': wsck
                              },
                      url='/tasks/check_featured_speaker')

        session = session_key.get()
        return self._copySessionToForm(session)
 def getConferencesCreated(self, request):
     """Return user created conferences."""
     # make sure user is authed
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException("Authorization required")
     # query conferences
     conferences = Conference.query(ancestor=ndb.Key(Profile, getUserId(user)))
     # profile key
     prof = ndb.Key(Profile, getUserId(user)).get()
     # return conf form obj
     return ConferenceForms(
         items=[self._copyConferenceToForm(conf, getattr(prof, "displayName")) for conf in conferences]
     )
Example #5
0
File: app.py Project: snady/blag
def user(username=""):
        error=""
        profile = []
        if username == "":
                return redirect("/login")
        else:
                if request.method == 'POST':
                        return redirect("/editprofile")
                else:
                        if utils.getUserId(username) == None:
                                error = "User does not exist!"
                        else:
                                userid = utils.getUserId(username)
                                profile = utils.getProfile(userid)
                        return render_template("myprofile.html", profile = profile, error = error)
    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'
        )
        return request
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""  # noqa
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Get user id by calling getUserId(user)
        user_id = getUserId(user)

        # Create a new key of kind Profile from the id.
        p_key = ndb.Key(Profile, user_id)

        # Get the entity from datastore by using get() on the key
        profile = p_key.get()

        # If profile doesn't exist, we create a new one
        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # Save the profile to datastore
            profile.put()

        return profile      # return Profile
    def _updateConferenceObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

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

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

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

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # special handling for dates (convert string to Date)
                if field.name in ("startDate", "endDate"):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == "startDate":
                        conf.month = data.month
                # write to Conference object
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()
        return self._copyConferenceToForm(conf, getattr(prof, "displayName"))
Example #9
0
 def _createWishlistObject(self, request):
     """add session into user profile"""
     # make sure user is authed
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     user_id = getUserId(user)
     
     #get user profile
     prof = ndb.Key(Profile, user_id).get()
     
     #get session
     session = ndb.Key(urlsafe=request.session_key).get()
     
     #raise exception if there is no session for the key
     if not session:
         raise endpoints.NotFoundException('No session found with key: %s' % request.session_key)
     
     #raise exception if the session is already added 
     if request.session_key in prof.wishlistSession:
         raise ConflictException("The session is already in your wishlist!")
     
     #add session wishlist to user profile
     prof.wishlistSession.append(request.session_key)
     prof.put()
     return BooleanMessage(data=True)
    def _getProfileFromUser(self):
        """Return user Profile from DataStore or create add new one if
        non-existent."""

        # Getting and Verifying current user
        user = getUser()
        
        # get the user_id (email) 
        user_id = getUserId(user)

        # Creating a profile key. 
        p_key = ndb.Key(Profile, user_id)
        
        # Using the profile key to get a profile Object
        profile = p_key.get()

        # create new Profile if not there
        if not profile:
            
            profile=Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),)
            
            profile.put()
        
        return profile 
Example #11
0
    def addSessionToWishlist(self, request):
        """Adds the session to the user's list of sessions they are interested in attending."""

        session_key = ndb.Key(urlsafe=request.sessionWSKey)

        # print 'session_key.kind(): ' + session_key.kind() + str(type(session_key.kind()))

        if session_key.kind() != 'Session':
            raise endpoints.BadRequestException("Session key is invalid")

        if not session_key.get():
            raise endpoints.NotFoundException("Session was not found")

        # session = session_key.get()

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

        wishlist = self._getWithlistByUserId(getUserId(user))

        wishlist.sessionKeysToAttend.append(request.sessionWSKey)
        wishlist.put()

        return BooleanMessage(data=True)
    def getConferenceSessionsByType(self, request):
        """Return sessions of a conference of a particular type."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create ancestor query for all key matches for this conference
        wsk = request.websafeConferenceKey
        sessionType = request.typeOfSession

        conf = ndb.Key(urlsafe=wsk).get()

        # query all sessions in this conference of a particular type
        sessions = Session.query(ancestor=ndb.Key(urlsafe=wsk))
        sessions = sessions.filter(Session.typeOfSession==sessionType)
        
        if not sessions:
            raise endpoints.NotFoundException(
                'No sessions found for conference with key: %s and type: %s'\
                 % wsk % sessionType)
        # return set of SessionForm objects per Session
        return SessionForms(
            items=[self._copySessionToForm(sess, wsk) for sess in sessions]
        )
Example #13
0
    def _createSpeakerObject(self, request):
        """Create Speaker object, returning SpeakerForm."""

        # check for auth'ed and valid user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Speaker name must be filled
        if not request.name:
            raise endpoints.BadRequestException("Field 'name' required")

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

        # allocate new Speaker ID
        s_id = Speaker.allocate_ids(size=1)[0]
        # make Speaker key from ID
        s_key = ndb.Key(Speaker, s_id)
        data['key'] = s_key

        # create Speaker & return SpeakerForm
        speaker = Speaker(**data)
        speaker.put()

        return self._copySpeakerToForm(speaker)
Example #14
0
 def _createConferenceObject(self, request):
     """Create or update Conference object, returning ConferenceForm/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("Conference 'name' field required")
     data = {field.name: getattr(request, field.name) for field in request.all_fields()}
     del data['websafeKey']
     del data['organizerDisplayName']
     for df in DEFAULTS:
         if data[df] in (None, []):
             data[df] = DEFAULTS[df]
             setattr(request, df, DEFAULTS[df])
     if data['startDate']:
         data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
         data['month'] = data['startDate'].month
     else:
         data['month'] = 0
     if data['endDate']:
         data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
     if data["maxAttendees"] > 0:
         data["seatsAvailable"] = data["maxAttendees"]
     p_key = ndb.Key(Profile, user_id)
     c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
     c_key = ndb.Key(Conference, c_id, parent=p_key)
     data['key'] = c_key
     data['organizerUserId'] = request.organizerUserId = user_id
     Conference(**data).put()
     taskqueue.add(params={'email': user.email(),
         'conferenceInfo': repr(request)},
         url='/tasks/send_confirmation_email'
     )
     return request
Example #15
0
    def getConferenceSessions(self, request):
        """Return all sessions in a given conference."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # sessions belong to conferences, so: websafe conference key given?
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("Field 'websafeConferenceKey' required")

        # websafe conference key good?
        try:
            c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        except Exception:
            raise endpoints.BadRequestException("websafeConferenceKey given is corrupted")
        if not c_key:
            raise endpoints.BadRequestException("websafeConferenceKey given is invalid") 

        # does the conference (still) exist?
        conf = c_key.get()
        if not conf:
            raise endpoints.NotFoundException("Conference with this key does not exist")

        # create ancestor query for all key matches for this user
        sessions = Session.query(ancestor=c_key)
        # return set of SessionForm objects per Conference
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )
    def getAvailableSessions(self, request):
        """Return sessions having spots available in a conference."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create ancestor query for all key matches for this conference
        wsk = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=wsk).get()

        sessions = Session.query(ancestor=ndb.Key(urlsafe=wsk))

        if not sessions:
            raise endpoints.NotFoundException(
                'No sessions found for this conference.')

        # check if available sessions exist

        # query by number of spots available
        sessions = sessions.filter(Session.spotsAvailable > 0)

        if not sessions:
            raise endpoints.NotFoundException(
                'No available sessions are found for this conference.')

        # return set of SessionForm objects per Session
        return SessionForms(
            items=[self._copySessionToForm(sess, "") for sess in sessions]
        )
Example #17
0
 def addSessionToWishlist(self, request):
     #TASK 2
     """Adds sessions to a user wishlist & returns the sessions added"""
     #Check if the user is logged in
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization Required')
     user_id = getUserId(user)
     #Validate that the SessionKey (urlsafe key) is provided
     if not request.SessionKey:
         raise endpoints.BadRequestException("SessionKey field required") 
     #Validate whether the requested SessionKey is already in the user's wishlist
     q = SessionWishlist.query()
     if (q.filter(SessionWishlist.sessionKey == request.SessionKey).count() > 0):
             raise endpoints.BadRequestException("SessionKey is already in %s's wishlist" % user)
     #Generate a Wishlist key to store the user wishlist. The wishlist will be created as
     #a child of Profile
     p_key = ndb.Key(Profile, user_id)
     w_id = SessionWishlist.allocate_ids(size=1, parent=p_key)[0]
     w_key = ndb.Key(SessionWishlist, w_id, parent=p_key)
     #Add the wishlist to the DS
     wishlist = SessionWishlist( key = w_key, sessionKey = request.SessionKey)
     wl_key = wishlist.put()
     #Return the session associated with the created entry
     session = ndb.Key(urlsafe=request.SessionKey).get()
     return self._copySessionToForm(session)
    def getSessionsByDate(self, request):
        """Return sessions having a particular date."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create date format
        if not request.sessionDate:
            raise endpoints.UnauthorizedException('A date value is required')
        else: 
            sessionDate = datetime.strptime(request.sessionDate[:10],\
             "%Y-%m-%d").date()

        # query by date
        sessions = Session.query()
        sessions = sessions.filter(Session.sessionDate==sessionDate)

        if not sessions:
            raise endpoints.NotFoundException(
                'No sessions found for this date.')

        # return set of SessionForm objects per Session
        return SessionForms(
            items=[self._copySessionToForm(sess, "") for sess in sessions]
        )
    def getSessionsBySpeaker(self, request):
        """Given a speaker, return all sessions given by this particular speaker, across all conferences"""

        # make sure user is logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

        # get speaker value from form request
        sessionSpeakerOfInterest = request.speaker

        # store all session objects across all conferences where this speaker is presenting
        all_sessions = []
        # query for conferences
        conferences = Conference.query()
        for conf in conferences:
            ck = getattr(conf, "key")
            wsck = ck.urlsafe()

            # For each conference, get Sessions for the Conference filtered by Speaker
            sessions = Session.query(Session.websafeConferenceKey == wsck)
            sessions = sessions.filter(Session.speaker == sessionSpeakerOfInterest)

            for session in sessions:
                all_sessions.append(session)

        # return sessions in all conferences
        return SessionForms(items=[self._copySessionToForm(session) for session in all_sessions])
 def getSessionsInWishlistByConference(self, request):
     """ List the wishlist items for the specified conference. """
     # validate the websafe conference key
     conference_key = validate_websafe_key(request.websafeConferenceKey,
                                           'Conference')
     # confirm the user
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required.')
     user_id = getUserId(user)
     user_key = ndb.Key(Profile, user_id)
     # get the user's wishlist sessions as a projection
     q_wishlist = WishList.query(ancestor=user_key)
     # wl_sessions = q_wishlist.fetch(1, projection=[WishList.sessions])
     wishlist = q_wishlist.fetch(1)[0]
     wishlist_session_keys = []
     # for session in wl_sessions:
     for session in wishlist.sessions:
         wishlist_session_keys.append(ndb.Key(urlsafe=session))
     # query Sessions where the specified Conference is the ancestor
     session_q = Session.query(ancestor=conference_key)
     # filter the Sessions to include only the sessions in the wishlist
     session_q = session_q.filter(Session.key.IN(wishlist_session_keys))
     # get the keys of those sessions, which are the ones we're looking for
     conf_session_keys = session_q.fetch(keys_only=True)
     # create a wishlist
     short_wishlist = WishList()
     # copy the found Session keys into the wishlist as websafe keys
     for key in conf_session_keys:
         short_wishlist.sessions.append(key.urlsafe())
     # return the reduced wishlist as a message
     return self._copyWishListToForm(short_wishlist)
    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())
Example #22
0
    def _updateConferenceObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

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

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.websafeConferenceKey)
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')
        for field in request.all_fields():
            data = getattr(request, field.name)
            if data not in (None, []):
                if field.name in ('startDate', 'endDate'):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == 'startDate':
                        conf.month = data.month
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()
        return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
    def getConferencesWithWishlistedSessions(self, request):
        """Returns conferences which have sessions the user has wishlisted."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        session_keys = [
            wl.sessionKey for wl in SessionWishlistItem.query(
                SessionWishlistItem.userId == user_id)]

        conf_keys = [ndb.Key(urlsafe=k).parent().urlsafe() for k in session_keys]

        conf_counts = {}
        for ck in conf_keys:
            if ck in conf_counts:
                conf_counts[ck] += 1
            else:
                conf_counts[ck] = 1

        confs = []
        for (k,v) in sorted(conf_counts.items(), key=operator.itemgetter(1)):
            confs.append(ConferenceWithWishlistSession(
                conference=self._copyConferenceToForm(
                    ndb.Key(urlsafe=k).get(), None),
                wishlistedSessions=v))

        return ConferencesWithWishlistSessionResponse(
            conferences=list(reversed(confs))
        )
    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
    def _createSessionWishlistObject(self, request):
        """Wishlists a session for the current user."""

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

        # check that session exists
        sessionKey = ndb.Key(urlsafe=request.sessionKey)
        if sessionKey.kind() != "ConferenceSession" or not sessionKey.get():
            raise endpoints.NotFoundException(
                'No session found with key: %s' % request.sessionKey)

        csession = sessionKey.get()

        q = SessionWishlistItem.query()
        q = q.filter(SessionWishlistItem.userId == user_id)
        q = q.filter(SessionWishlistItem.sessionKey == request.sessionKey)

        # if session has already been wishlisted by this user, simply return
        # success
        if q.count() > 0:
            return BooleanMessage(data=True)

        wlItem = SessionWishlistItem()
        wlItem.userId = user_id
        wlItem.sessionKey = request.sessionKey
        wlItem.put()

        return BooleanMessage(data=True)
Example #26
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # TODO 1 X
        # step 1. copy utils.py from additions folder to this folder
        #         and import getUserId from it
        # step 2. get user id by calling getUserId(user)
        # step 3. create a new key of kind Profile from the id

        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)

        # TODO 3 X
        # get the entity from datastore by using get() on the key
        profile = p_key.get()
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(),
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            # TODO 2 X
            # save the profile to datastore
            profile.put()

        return profile      # return Profile
Example #27
0
    def getSessionsBySpeaker(self, request):
        """Return sessions having the same speaker across conferences."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create ancestor query for all key matches for this conference
        first = request.speakerFirst
        last = request.speakerLast
        fullname = str(first)+" "+str(last)

        # query all sessions by speaker names
        sessions = Session.query()
        sessions = sessions.filter(Session.speakerLast==last)
        sessions = sessions.filter(Session.speakerFirst==first)

        if not sessions:
            raise endpoints.NotFoundException(
                'No sessions found for speaker with name: %s' % fullname)

        # return set of SessionForm objects per Session
        return SessionForms(
            items=[self._copySessionToForm(sess, "") for sess in sessions]
        )
Example #28
0
    def getConferencesToAttend(self, request):
        """Get list of conferences that user has registered for."""
        # TODO:
        # step 1: get user profile
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        # step 2: get conferenceKeysToAttend from profile.
        # to make a ndb key from websafe key you can use:
        # ndb.Key(urlsafe=my_websafe_key_string)
        list_of_keys = []
        for key in profile.conferenceKeysToAttend:
            list_of_keys.append(ndb.Key(urlsafe=key))
        # step 3: fetch conferences from datastore. 
        # Use get_multi(array_of_keys) to fetch all keys at once.
        # Do not fetch them one by one!
        conferences = ndb.get_multi(list_of_keys)

        # return set of ConferenceForm objects per Conference
        return ConferenceForms(items=[self._copyConferenceToForm(conf, "")\
         for conf in conferences]
        )
Example #29
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 _addSessionToWishlist(self, request):
     #Check if the user is logged in
     
     user = self._getLoggedInUser()
     user_id = getUserId(user)
         
     #Check if the theSession exists
     theSession = ndb.Key(urlsafe=request.websafeSessionKey).get()
     
     if not theSession:
         raise endpoints.BadRequestException("Invalid session key")
     
     #Get user profile
     prof = ndb.Key(Profile, user_id).get()
     
     if not prof:
         raise endpoints.BadRequestException("Unable to find user profile")
     
     wishlistEntry = UserWishlist.query(ancestor=prof.key).filter(
         getattr(UserWishlist, "wishlistedSessionKey") == request.websafeSessionKey
     ).get()
     
     print wishlistEntry
     
     #If the desired wishlist entry doesn't already exist, create it.
     if not wishlistEntry:
         wishlistEntry = UserWishlist(parent=prof.key)
         setattr(wishlistEntry, "wishlistedSessionKey", request.websafeSessionKey)
         wishlistEntry.put()
         
     return self._getUserWishlistByProfile(prof)     
Example #31
0
 def getSessionsInWishlist(self, request):
     """Return list of Sessions the user has in there wish list."""
     # make sure user is authorized
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     # get Profile from datastore
     user_id = getUserId(user)
     p_key = ndb.Key(Profile, user_id)
     profile = p_key.get()
     # look up the sessions based on SessionKey in the profile.sessionKeysWishList
     s_keys = [ndb.Key(urlsafe=wsk) for wsk in profile.sessionKeysWishList]
     sessions = ndb.get_multi(s_keys)
     # return set of SessionForm objects one per Session
     return SessionForms(
         items=[self._copySessionToForm(sesn) for sesn in sessions])
Example #32
0
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create ancestor query for all key matches for this user
        confs = Conference.query(ancestor=ndb.Key(Profile, user_id))
        prof = ndb.Key(Profile, user_id).get()
        # return set of ConferenceForm objects per Conference
        return ConferenceForms(items=[
            self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
            for conf in confs
        ])
Example #33
0
    def removeSessionFromWishList(self, request):
        """Removes the specific Session from the wishlist"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)
        parent_key = ndb.Key(Profile, user_id)
        qw = WishList.query(ancestor=parent_key)
        # Filter the result finding the session in the wishlist
        qw = qw.filter(WishList.sessionKey == request.websafeSessionKey)
        for wl in qw:
            # Delete the entity from data store.
            wl_ent = wl.key.delete()

        return StringMessage(data='Session removed from wishlist')
Example #34
0
    def create_session(self, request):
        """Create a new session for a specified conference."""
        try:
            date = datetime.strptime(request.date, "%Y-%m-%d").date()
        except ValueError:
            raise endpoints.BadRequestException(
                "Date must be in format YYYY-MM-DD.")
        try:
            start_time = datetime.strptime(request.start_time, '%H:%M').time()
        except ValueError:
            raise endpoints.BadRequestException(
                "Time must be in format HH-MM (24 hour clock).")

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required.")

        conference = self._get_entity_by_key(request.conference)

        if getUserId(user) != conference.organizerUserId:
            raise endpoints.ForbiddenException(
                "Only the conference organizer can add sessions.")

        speaker = self._get_entity_by_key(request.speaker_key)

        # Logged-in user; can add sessions to this conference

        allocated_id = ndb.Model.allocate_ids(size=1, parent=conference.key)[0]
        session_key = ndb.Key(Session, allocated_id, parent=conference.key)

        session = Session(key=session_key,
                          name=request.name,
                          highlights=request.highlights,
                          speaker_key=speaker.key,
                          duration=request.duration,
                          type_of_session=request.type_of_session,
                          date=date,
                          start_time=start_time)
        session.put()

        taskqueue.add(params={
            'speaker_key': speaker.key.urlsafe(),
            'conference_key': conference.key.urlsafe()
        },
                      url='/tasks/store_featured_speaker')

        return session.to_message()
    def addSessionToWishlist(self, request):
        """Add a session to the current user's wishlist"""
        # Get current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        profile = ndb.Key(Profile, user_id).get()
        session_key = ndb.Key(urlsafe=request.websafeSessionKey)
        if session_key not in profile.sessionWishlist:
            profile.sessionWishlist.append(session_key)
            profile.put()
        else:
            raise endpoints.BadRequestException(
                'Session to add already exists in the user\'s wishlist')
        return StringMessage(data='Session added to wishlist')
Example #36
0
    def getSessionsInWishlist(self, request):
        """Query session a user wishes to attend in a conference"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        wls = WishlistSession.query(WishlistSession.userId == user_id)
        if hasattr(request, 'websafeConferenceKey'):
            if request.websafeConferenceKey:
                wls = wls.filter(WishlistSession.sessionConferenceKey ==
                                 request.websafeConferenceKey)
        sessions = ndb.get_multi(
            [ndb.Key(urlsafe=wishList.sessionKey) for wishList in wls])

        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions])
    def _updateConferenceObject(self, request):
        """ Update the fields in the conference model. """
        # make sure the user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user, id_type="oauth")

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

        # update existing conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

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

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

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # special handling for dates (convert string to Date)
                if field.name in ("startDate", "endDate"):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == "startDate":
                        conf.month = data.month
                # write to Conference object
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()

        # return the conference form
        return self._copyConferenceToForm(conf, getattr(prof, "displayName"))
Example #38
0
def post(postid):
    if usersession() == "":
        return redirect("/login")
    if request.method == 'POST':
        content = str(request.form['name'])
        utils.writeComment(content, utils.getUserId(session['user']), postid)
    postrow = utils.getPost(postid)
    commentrow = utils.getCommentsOnPost(postid)
    users = []
    for comment in commentrow:
        users.append(comment[2])
    size = len(users)
    return render_template("post.html",
                           postrow=postrow,
                           commentrow=commentrow,
                           users=users,
                           size=size)
Example #39
0
    def _verifyConfCreator(self, websafeKey):
        """helper function to check if conf was created by current user"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

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

        # check that user is conference creator
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')
    def deleteSessionInWishlist(self, request):
        """Delete a session in the user's wishlist"""
        # Get current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        profile = ndb.Key(Profile, user_id).get()
        session_key = ndb.Key(urlsafe=request.websafeSessionKey)
        if session_key in profile.sessionWishlist:
            profile.sessionWishlist.remove(session_key)
            profile.put()
        else:
            raise endpoints.BadRequestException(
                'Session to delete does not exist in the user\'s wishlist')
        return StringMessage(data='Session deleted from wishlist')
Example #41
0
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
      
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

     
        p_key = ndb.Key(Profile, getUserId(user))
       
        conferences = Conference.query(ancestor=p_key)
       
        prof = p_key.get()
        displayName = getattr(prof, 'displayName')
    
        return ConferenceForms(
            items=[self._copyConferenceToForm(conf, displayName) for conf in conferences]
        )    
Example #42
0
    def getSessionsInWishlist(self, request):
        """Query for all the sessions in a conference that the user is
        interested in."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        wishs = Wishlist.query(Wishlist.user == user_id)

        session_keys = [
            ndb.Key(urlsafe=wish.websafeSessionKey) for wish in wishs
        ]
        sessions = ndb.get_multi(session_keys)

        # return set of SessionForm objects per Session
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions])
    def getSessionsInWishlist(self, request):
        """Query for all the sessions in a conference that the user is
        interested in."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'You must be logged in to use this method.')

        user_id = getUserId(user)
        prof = ndb.Key(Profile, user_id).get()
        if not prof:
            raise endpoints.NotFoundException('Profile not found.')
        wishlist = prof.wishList
        wishlist_keys = [ndb.Key(urlsafe=wish) for wish in wishlist]
        wishlist_sessions = ndb.get_multi(wishlist_keys)
        return SessionForms(items=[
            self._copySessionToForm(wish) for wish in wishlist_sessions
        ])
Example #44
0
    def getAttendeesForConference(self, request):
        """Get attendees for given conference"""
        #check if user is owner
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

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

        ps = Profile.query(
            Profile.conferenceKeysToAttend == request.websafeConferenceKey)

        return ProfileForms(profiles=[self._copyProfileToForm(p) for p in ps])

        return self._conferenceRegistration(request)
Example #45
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)
        user_key = ndb.Key(Profile, user_id)

        profile = user_key.get()
        if not profile:
            profile = Profile(key=user_key,
                              displayName=user.nickname(),
                              mainEmail=user.email(),
                              teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED))
            profile.put()

        return profile
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        
        # Getting and Verifying current user
        user = getUser()

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

        # create ancestor query for all key matches for this user
        conferences = Conference.query(ancestor=ndb.Key(Profile, user_id))
        
        prof = ndb.Key(Profile, user_id).get()
        
        # return one or many ConferenceForm objects
        return ConferenceForms(
            items = [self._copyConferenceToForm(
                conf, getattr(prof, 'displayName')) for conf in conferences])
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # make profile key
        p_key = ndb.Key(Profile, getUserId(user))
        # create ancestor query for this user
        conferences = Conference.query(ancestor=p_key)
        # get the user profile and display name
        prof = p_key.get()
        displayName = getattr(prof, 'displayName')
        # return set of ConferenceForm objects per Conference
        return ConferenceForms(
            items=[self._copyConferenceToForm(conf, displayName) for conf in conferences]
        )
Example #48
0
    def addSessionToWishlist(self, request):
        """This function adds given session to wishlist."""
        # check for authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # check for SessionKey
        if not request.SessionKey:
            raise endpoints.BadRequestException("'SessionKey' field required")

        # Try and get the session object
        s_key = ndb.Key(urlsafe=request.SessionKey)
        sess = s_key.get()
        if not sess:
            raise endpoints.NotFoundException('No Session found with key: %s' %
                                              request.SessionKey)

        # Add to wishlist
        # get Profile from datastore
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        if not profile:
            raise endpoints.NotFoundException('No profile found')

        # Check that the session does not already exist
        # Prevent the same session from being added to wishlist
        query = Wishlist.query(ancestor=p_key)
        query = query.filter(Wishlist.sessionKey == request.SessionKey)
        if len(query.fetch()) != 0:
            raise endpoints.BadRequestException(
                "That session is already in your wishlist")

        # generate Wishlist ID based on User ID
        w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        w_key = ndb.Key(Wishlist, w_id, parent=p_key)

        # save new wishlist to datastore
        newWish = Wishlist(sessionKey=request.SessionKey)
        newWish.key = w_key
        newWish.put()

        return request
Example #49
0
    def deleteSessionInWishlist(self, request):
        """Delete a session from the user's wishlist."""
        wssk = request.websafeSessionKey
        retval = False

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

        # Get the user profile and remove the session if it's there
        user_id = getUserId(user)
        profile = ndb.Key(Profile, user_id).get()
        if wssk in profile.sessionWishlist:
            profile.sessionWishlist.remove(wssk)
            retval = True

        # Update the profile
        profile.put()
        return BooleanMessage(data=retval)
    def _createWishlistObject(self, request):
        """Create or update Wishlist object, returning WishlistForm/request."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # check sessionName exists
        if not request.sessionName:
            raise endpoints.UnauthorizedException('Name required')
        # get userId
        user_id = getUserId(user)

        # get session key
        this_session = Session.query(Session.name == request.sessionName).get()

        # populate dict
        data = {
            'userId': user_id,
            'sessionName': request.sessionName,
            'sessionKey': this_session.key,
            'typeOfSession': this_session.typeOfSession
        }

        # generate wishlist key from session key
        p_key = this_session.key
        c_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Wishlist, c_id, parent=p_key)
        data['key'] = c_key

        # query wishlist, filter by userId and sessionName, then count
        q = Wishlist.query()
        q = q.filter(Wishlist.userId == user_id)

        # if this session already in user's wishlist, bounce
        for i in q:
            if i.sessionKey == this_session.key:
                raise endpoints.UnauthorizedException(
                    'Session already added to wishlist')

        # save to wishlist
        Wishlist(**data).put()
        return request
    def deleteSessionInWishlist(self, request):
        """Removes the session from the user's list of sessions they are
        interested in attending."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'You must be logged in to use this method.')

        user_id = getUserId(user)

        prof = ndb.Key(Profile, user_id).get()
        # verify that the session is in the user's wishlist.
        if request.websafeSessionKey not in prof.wishList:
            raise endpoints.NotFoundException('Session not on wishlist.')

        prof.wishList.remove(request.websafeSessionKey)
        prof.put()

        return self._copyProfileToForm(prof)
Example #52
0
    def deleteFromWishlist(self, request):
        """Remove session with given key from wishlist."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()

        session = ndb.Key(urlsafe=request.sessionKey).get()
        if not session:
            raise endpoints.NotFoundException('No session found with key: %s' %
                                              request.sessionKey)
        if request.sessionKey in profile.SessionKeysInWishList:
            profile.SessionKeysInWishList.remove(request.sessionKey)

        profile.put()

        return BooleanMessage(data=True)
Example #53
0
    def _updateConferenceObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

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

        # update existing conference
        try:
            conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        except:
            conf = None
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found for key: %s' \
                % request.websafeConferenceKey)

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

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # special handling for dates (convert string to Date)
                if field.name in ('startDate', 'endDate'):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == 'startDate':
                        conf.month = data.month
                # write to Conference object
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()
        return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
    def _createSpeakerObject(self, request):
        """
        Creates a Speaker entity in datastore based on the information provided
        by client.
        Sends a confirmation email after adding the new Speaker
        """
        # 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("Speaker 'name' \
                field required")

        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeSpeakerKey']

        # create Speaker & return (modified) SpeakerForm
        speaker_key = Speaker(**data).put()
        taskqueue.add(params={
            'email': user.email(),
            'speakerInfo': repr(request)
        },
                      url='/tasks/send_speaker_confirmation_email')
        # Return data as SpeakerForm
        speakerform = SpeakerForm()

        for field in speakerform.all_fields():
            if data.has_key(field.name):
                setattr(speakerform, field.name, data[field.name])
            # Checks if the field is websafeSpeakerKey, then converts it into
            # urlsafe key
            elif field.name == "websafeSpeakerKey":
                setattr(speakerform, field.name, speaker_key.urlsafe())

        speakerform.check_initialized()
        return speakerform
Example #55
0
    def addSessionToWishlist(self, request):
        """Add a sessions to a profiles wish to attend wishlist."""
        retval = False
        wssk = request.websafeSessionKey
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Get the session
        session = ndb.Key(urlsafe=wssk).get()
        if not session:
            raise endpoints.NotFoundException(
                'No session found with key: {}'.format(wssk))

        # Get the profile
        user_id = getUserId(user)
        profile = ndb.Key(Profile, user_id).get()

        # Check that it's not already on the wishlist
        if wssk in profile.sessionWishlist:
            raise ConflictException(
                "This session is already in your wishlist.")

        # Check that the session is in a conference the user is registered in
        if profile.conferenceKeysToAttend:
            seshs = [
                Session.query(ancestor=ndb.Key(urlsafe=p_key))
                for p_key in profile.conferenceKeysToAttend
            ]
            if not seshs:
                raise endpoints.ForbiddenException(
                    "You are not attending the conference that this session is in."
                )
            profile.sessionWishlist.append(wssk)
            profile.put()
            retval = True
        else:
            raise endpoints.ForbiddenException(
                "You are not attending the conference that this session is in."
            )

        return BooleanMessage(data=retval)
Example #56
0
    def _createSpeakerObject(self, request):
        """Create speaker object"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        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()
        }

        s_key = Speaker(**data).put()

        return request
Example #57
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        ## TODO 2
        ## step 1: make sure user is authed
        ## uncomment the following lines:
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # get Profile from datastore
        print "***********"
        print user
        logging.info('**1**** %s',user)
        user_id = getUserId(user)
        print "**********"
        print user_id
        logging.info('**2**** %s',user_id)
        p_key = ndb.Key(Profile, user_id)
        print "*********"
        print p_key
        logging.info('***3**** %s',p_key)
        profile = p_key.get()
        print "*********"
        print profile
        logging.info('****4**** %s',profile)


        ## step 2: create a new Profile from logged in user data
        ## you can use user.nickname() to get displayName
        ## and user.email() to get mainEmail
        if not profile:
            profile = Profile(
                # userId = None,
                key = p_key,
                displayName = user.nickname, 
                mainEmail= user.email,
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()

        return profile      # return Profile
Example #58
0
    def getProfileByEmail(self, request):
        """This is more of an admin function which allows a conference
        organizer to get a registered users profile by email address.
        This will more useful in the future if more properties and user
        details are added to the profile."""

        # verify user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        conf = ndb.Key(urlsafe=request.conferenceKey)
        if not conf:
            raise endpoints.NotFoundException('No conference found: %s' %
                                              request.conferenceKey)

        # verify user is conference organizer
        if conf.parent() != ndb.Key(Profile, getUserId(user)):
            raise endpoints.ForbiddenException(
                'You must be the conference organizer '
                'to view users profiles')

        # get profile by email from datastore
        profile = Profile.query(Profile.mainEmail == request.mainEmail)

        # verify user profile key is registered in conference
        # with conference organizer
        for prof in profile:
            if request.conferenceKey not in prof.conferenceKeysToAttend:
                raise endpoints.ForbiddenException(
                    'User is not registered in Conference Organizers conference.'
                )

        # verify email and profile exists
        if not request.mainEmail or not profile:
            raise endpoints.NotFoundException(
                'Profile or email not found: %s - %s' %
                (profile, request.mainEmail))

        return EmailForms(
            items=[self._copyProfileToForm(prof) for prof in profile])
    def addSessionToWishlist(self, request):
        """Add Session to Wishlist"""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get Session object from request; bail if not found
        try:
            sess = ndb.Key(urlsafe=request.websafeSessionKey)
            kind = sess.kind()
            sess = sess.get()

            # check if the key is a Session Kind
            if not sess or kind != 'Session':
                raise endpoints.NotFoundException(
                    'No session found with key: %s' % request.websafeSessionKey)
        except Exception, e:
            raise endpoints.NotFoundException(
                'No session found with key: %s' % request.websafeSessionKey)
    def deleteSessionInWishList(self, request):
        """Remove requested wishlist by user."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        wishlists = WishList.query(ancestor=ndb.Key(Profile, user_id))
        ws = wishlists.filter(WishList.session_key == request.session_key)

        wrpt = WishListReport()

        if ws.count():
            for w in ws:
                w.key.delete()
            setattr(wrpt, 'rpt', 'OK')
        else:
            setattr(wrpt, 'rpt', 'Not Found')

        wrpt.check_initialized()
        return wrpt