def _createConferenceSessionObject(self, request): """Create ConferenceSession object.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # extract session form data = { field.name: getattr( request, field.name) for field in request.all_fields()} del data['conferenceKey'] # check that conference exists confKey = ndb.Key(urlsafe=request.conferenceKey) if confKey.kind() != "Conference" or not confKey.get(): raise endpoints.NotFoundException( 'No conference found with key: %s' % request.conferenceKey) conf = confKey.get() # check that user is owner if user_id != conf.organizerUserId: raise endpoints.ForbiddenException( 'Only the owner can add sessions to a conference.') # convert dates from strings to Date objects; set month based on # start_date data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date() data['typeOfSession'] = str(data['typeOfSession']) cs_id = ConferenceSession.allocate_ids(size=1, parent=confKey)[0] cs_key = ndb.Key(ConferenceSession, cs_id, parent=confKey) data['key'] = cs_key data['createdTime'] = int(calendar.timegm(time.gmtime())) cs = ConferenceSession(**data).put() # add a task to update the featured speaker taskqueue.add( params={ 'speaker': request.speaker, 'conferenceKey': request.conferenceKey}, url='/tasks/update_featured_speaker') return self._copyConferenceSessionToForm(cs.get())
def getConferenceSessionsByFilters(self, request): """Query for the sessions that are not specified type and are not running after specified time """ # first get the sessions that don't have the specified type # then get the sessions that don't run past the specified time type_f = request.websafeType print type_f print '------------------------------' time_f = request.websafeTime print time_f print '------------------------------' eq_f = request.websafeOperator print eq_f print '------------------------------' q = ConferenceSession.query(ConferenceSession.type != type_f) print q sessions=[] for sess in q: if sess.start_time is not None: if eq_f == '<': if sess.start_time < datetime.strptime(time_f, '%H:%M').time(): # add the session to the sessions sessions.append(sess) elif eq_f == '=': if sess.start_time == datetime.strptime(time_f, '%H:%M').time(): # add the session to the sessions sessions.append(sess) elif eq_f == '>': if sess.start_time > datetime.strptime(time_f, '%H:%M').time(): # add the session to the sessions sessions.append(sess) return ConferenceSessionForms( items=[self._copySessionToForm(s) for s in sessions] )
def deleteConference(self, request): """Delete conference.""" wsck = request.websafeConferenceKey conf = self._retrieveConference(wsck) if not conf: raise endpoints.NotFoundException('No conference found with key: %s' % wsck) # Remove the link between the sessions and this conference conf_sess = ConferenceSession.query(ancestor=conf.key) if conf_sess: for sess in conf_sess: wssk = sess.key.urlsafe() # Get all the wishlists that have this session in them and remove this session from them wishes = Wishlist.query(ndb.AND(Wishlist.sessions == wssk)) for wish in wishes: if wish and wssk in wish.sessions: wish.sessions.remove(wssk) wish.put() sess.key.delete() # Unregister the users from this conference if they are registered for it registered_users = Profile.query(ndb.AND(Profile.conferenceKeysToAttend == wsck)) if registered_users: for reg_user in registered_users: if reg_user and wsck in reg_user.conferenceKeysToAttend: reg_user.conferenceKeysToAttend.remove(wsck) reg_user.put() conf.key.delete() return BooleanMessage(data=True)
def getSessionsBySpeaker(self, request): """Query for sessions with a given speaker""" q = ConferenceSession.query(ConferenceSession.speakers.name == request.websafeSpeaker) q.order(ConferenceSession.start_time) return ConferenceSessionForms( items=[self._copySessionToForm(sess) for sess in q] )
def _cacheSpeakerAndSession(speaker_key, conf_key): """Assign Speaker and their Session to memcache; used by memcache cron job """ session_message = "" # Make sure the conference and speaker are both valid if conf_key and speaker_key: conf = ndb.Key(urlsafe=conf_key).get() speaker = ndb.Key(urlsafe=speaker_key).get() if conf and speaker: # Now retrieve all sessions for that conference at which this speaker will speak sessions = ConferenceSession.query(ancestor=conf.key)\ .filter(ndb.AND(ConferenceSession.speakerUserId == speaker_key))\ .fetch(projection=[Conference.name]) # If this speaker is supposed to speak at multiple sessions, # throw a summary of all their sessions into the task queue if sessions and len(sessions) > 1: session_message = '%s %s %s' % ( speaker.displayName, 'will be speaking at the following sessions: ', ', '.join(sess.name for sess in sessions)) memcache.set(speaker.mainEmail, session_message) else: memcache.delete(speaker.mainEmail) elif not conf: logging.error('No conference found with key: %s' % conf_key) elif not speaker: logging.error('No speaker found with key: %s' % speaker_key) elif not conf_key: logging.error('No conference key was provided') elif not speaker_key: logging.error('No speaker key was provided') return session_message
def getAllSessionsByType(self, request): """Given a conference, return all sessions of a specified type (eg lecture, keynote, workshop)""" sessions = ConferenceSession.query(ndb.AND(ConferenceSession.typeOfSession == request.sessionType)) # return set of ConferenceSessionForm objects per ConferenceSession return ConferenceSessionForms( items=[self.toConferenceSessionForm(cs) for cs in sessions] )
def getSessionsFromSpeakerAndConference(self, request): '''Given a speaker and a conference return all sessions that have that speaker''' # get speaker key and make sure we have a speaker speaker_key = self.get_websafe_key( request.websafeSpeakerKey, "ConferenceSpeaker") speaker = speaker_key.get() if not speaker: raise endpoints.NotFoundException( "The speaker you are looking for was not found!") # get conference key and make sure we have a conference conf_key = self.get_websafe_key( request.websafeConferenceKey, "Conference") conference = conf_key.get() if not conference: raise endpoints.NotFoundException( "The conference you are looking for was not found!") q = ConferenceSession.query(ancestor=conf_key) q = q.filter(ConferenceSession.speakerKey == speaker_key) sessions = q.fetch(50) return mm.ConferenceSessionForms( items=[sessions[i].to_form(speaker) for i in range(len(sessions))])
def getConferenceSessionsByType(self, request): ''' Create Session to Conference, open only to the conference Organizer''' # Limit the amount of types one can include: if len(request.typeOfSession) > 5: raise endpoints.BadRequestException( "Maximum number of typeOfSession to include is 5") # get the conference confKey = self.get_websafe_key( request.websafeConferenceKey, "Conference") conf = confKey.get() if not conf: raise endpoints.BadRequestException( "This conference does not exist: %s" % confKey) # query ConferenecSession q = ConferenceSession.query(ancestor=confKey) types = request.typeOfSession if types: q = q.filter(ConferenceSession.type.IN(types)) q = q.order(ConferenceSession.name) sessions = q.fetch(100) speaker_keys = [] for sess in q: speaker_keys.append(sess.speakerKey) speakers = ndb.get_multi(speaker_keys) return mm.ConferenceSessionForms( items=[sessions[i].to_form(speakers[i]) for i in range(len(sessions))])
def getAllSessions(self, request): """return all sessions""" conf_sess = ConferenceSession.query() # return set of ConferenceSessionForm objects return ConferenceSessionForms( items=[self.toConferenceSessionForm(cs) for cs in conf_sess] )
def getSessionsBySpeaker(self, request): """Return a list of sessions associated with this conference limited by session speaker.""" sessions = ConferenceSession.query(ConferenceSession.speaker == request.speakerPath) # return all matched Sessions as SessionForms return SessionForms( items=[self._copySessionToForm(sess, sess.websafeConferenceKey) for sess in sessions] )
def getSessionsBySpeaker(self, request): """Given a speaker, return all sessions given by this particular speaker, across all conferences""" conf_sess = ConferenceSession.query(ndb.AND(ConferenceSession.speakerUserId == request.speakerUserId)) speaker = self._getSpeaker(request.speakerUserId) # return set of ConferenceSessionForm objects per ConferenceSession return ConferenceSessionForms( items=[self.toConferenceSessionForm(cs, getattr(speaker, 'displayName')) for cs in conf_sess] )
def getSessionsBySpeaker(self, request): """Retrieves sessions matching the request query""" q = ConferenceSession.query( ConferenceSession.speaker == request.speaker) return ConferenceSessionForms( items=[self._copyConferenceSessionToForm(cs) for cs in q] )
def getConferenceSessionsByConfId(self, request): """Retrieves sessions matching the request query""" q = ConferenceSession.query(ancestor=ndb.Key( urlsafe=request.conferenceKey)) return ConferenceSessionForms( items=[self._copyConferenceSessionToForm(cs) for cs in q] )
def getConferenceSessions(self, request): """Query for sessions, given a conference""" # query for the conference, and then query for the sessions by conference key conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() q = ConferenceSession.query(ancestor=conf.key) q.order(ConferenceSession.start_time) return ConferenceSessionForms( items=[self._copySessionToForm(sess) for sess in q] )
def getConferenceSessionsByType(self, request): """Query for sessions, given the type""" conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() q = ConferenceSession.query(ancestor=conf.key) q = q.filter(ConferenceSession.type == request.websafeType) q.order(ConferenceSession.start_time) return ConferenceSessionForms( items=[self._copySessionToForm(sess) for sess in q] )
def _createSessionObject(self, request): """Create ConferenceSession object, returning ConferenceSessionForm/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("ConferenceSession 'name' field required") if not request.speaker: raise endpoints.BadRequestException("ConferenceSession 'speaker' field required") # check if conf exists given websafeConfKey # get conference; check that it exists conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException('No conference found with key: %s' % request.websafeConferenceKey) # Check to see if user is Conference Organiser if conf.organizerUserId != user_id: raise endpoints.NotFoundException('Only the conference organiser %s can add conference sessions.' % conf.organizerUserId) # copy ConferenceSessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['websafeKey'] # convert dates from strings to Date objects; set month based on start_date if data['startDate']: data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date() # convert startTime from strings to Time objects if data['startTime']: data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time() # convert duration from strings to Time objects if data['duration']: data['duration'] = datetime.strptime(data['duration'][:5], "%H:%M").time() # generate Profile Key based on user ID and ConferenceSession # ID based on Profile key get ConferenceSession key from ID p_key = ndb.Key(Profile, user_id) c_id = ConferenceSession.allocate_ids(size=1, parent=p_key)[0] c_key = ndb.Key(ConferenceSession, c_id, parent=p_key) data['key'] = c_key data['organizerUserId'] = request.organizerUserId = user_id # create ConferenceSession, send email to organizer confirming # creation of ConferenceSession & return (modified) ConferenceSessionForm ConferenceSession(**data).put() #taskqueue.add(params={'email': user.email(), 'conferenceSessionInfo': repr(request)}, url='/tasks/send_confirmation_session_email') taskqueue.add(params={'websafeConferenceKey': request.websafeConferenceKey, 'speaker': data['speaker'], 'conferenceInfo': repr(request)}, url='/tasks/getFeaturedSpeaker') return self._copyConferenceSessionToForm(request)
def getConferenceSessionsByHighlight(self, request): """Query for sessions with the given highlight""" q = ConferenceSession.query(ConferenceSession.highlights.IN([request.websafeHighlight])) if q is not None: return ConferenceSessionForms( items=[self._copySessionToForm(sess) for sess in q] ) return ConferenceSessionForms( items=[] )
def getConferenceSessions(self, request): """Return a list of sessions associated with this conference.""" confKey = ndb.Key(urlsafe=request.websafeConferenceKey) sessions = ConferenceSession.query(ancestor=confKey) if not sessions: raise endpoints.NotFoundException( 'No sessions found with key: %s' % request.websafeConferenceKey) # return all matched Sessions as SessionForms return SessionForms( items=[self._copySessionToForm(sess, request.websafeConferenceKey) for sess in sessions] )
def getConferenceSessionsByMaxDuration(self, request): """Return a list of sessions associated with this conference limited by MAX duration.""" sessions = ConferenceSession.query(ndb.AND(ConferenceSession.websafeConferenceKey == request.websafeConferenceKey,ConferenceSession.duration <= request.duration)) if not sessions: raise endpoints.NotFoundException( 'No sessions found with key: %s' % request.websafeConferenceKey) # return all matched Sessions as SessionForms return SessionForms( items=[self._copySessionToForm(sess, request.websafeConferenceKey) for sess in sessions] )
def post(self): """Establish if a speaker is duplicated and adds it to the Featured Speaker memcache if it is.""" confKey = ndb.Key(urlsafe=self.request.get('websafeConferenceKey')) sessions = ConferenceSession.query(ancestor=confKey).filter(ConferenceSession.speaker == self.request.get('speaker')) if(sessions.count() > 1): featured_speakers = '%s %s %s' % ( 'The featured speaker ', self.request.get('speaker'), ' is hosting the following sessions:' ' '.join(sess.name for sess in sessions)) memcache.set(MEMCACHE_FEATURED_SPEAKERS_KEY, featured_speakers)
def getConferenceSessionsByType(self, request): """Retrieves sessions matching the request query""" q = ConferenceSession.query(ancestor=ndb.Key( urlsafe=request.conferenceKey)) q = q.filter( ConferenceSession.typeOfSession == str( request.typeOfSession)) return ConferenceSessionForms( items=[self._copyConferenceSessionToForm(cs) for cs in q] )
def getConferenceSessions(self, request): """Given a conference, return all sessions""" profile = self._getUserProfile() conf = self._retrieveConference(request.websafeConferenceKey) if not conf: raise endpoints.NotFoundException('No conference found with key: %s' % request.websafeConferenceKey) conf_sess = ConferenceSession.query(ancestor=conf.key) # return set of ConferenceSessionForm objects per ConferenceSession return ConferenceSessionForms( items=[self.toConferenceSessionForm(cs) for cs in conf_sess] )
def getConferenceSessionsByType(self, request): """Given a conference, return all sessions of a specified type (eg lecture, keynote, workshop)""" conf = self._retrieveConference(request.websafeConferenceKey) if not conf: raise endpoints.NotFoundException('No conference found with key: %s' % request.websafeConferenceKey) sessions = ConferenceSession.query(ancestor=conf.key)\ .filter(ndb.AND(ConferenceSession.typeOfSession == request.sessionType)) # return set of ConferenceSessionForm objects per ConferenceSession return ConferenceSessionForms( items=[self.toConferenceSessionForm(cs) for cs in sessions] )
def _setFeaturedSpeaker(conference_key, speaker_name): """ Checks whether the speaker is a featured speaker or not and if they are, will set them into memcache with the sessions they speak in :param conference_key: the conference key :param speaker_name: the speaker name """ conf = ndb.Key(urlsafe=conference_key).get() q = ConferenceSession.query(ancestor=conf.key) q = q.filter(ConferenceSession.speakers.name.IN([speaker_name])) session_names=[sess.name for sess in q] if q.count(limit=2) > 1: memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY, speaker_name) memcache.set(MEMCACHE_FEATURED_SESSIONS_KEY, session_names)
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') if not request.parent_key: raise endpoints.BadRequestException("Session 'parent_key' field required") data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['parent_key'] if data['start_time']: # assumed that start time is given in 24 hour time :) t = datetime.strptime(data['start_time'], '%H:%M') t = t.time() data['start_time'] = t if data['date']: data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date() data['speakers'] = [] for s in request.speakers: data['speakers'].append(Speaker(name=s)) conf = ndb.Key(urlsafe=request.parent_key).get() sess = ConferenceSession(parent=conf.key, **data) sess.put() # start the task to find a featured speaker # if there are multiple speakers check each one for speaker in data['speakers']: taskqueue.add(params={'conf_key': request.parent_key, 'speaker_name': speaker.name}, url='/tasks/set_featured_speaker' ) return request
def _updateFeaturedSpeaker(speaker, conferenceKey): """Updates the featured speaker in memcache.""" conf = ndb.Key(urlsafe=conferenceKey) if conf.kind() != "Conference" or not conf.get(): raise endpoints.NotFoundException( 'No conference found with key: %s' % conferenceKey) q = ConferenceSession.query(ancestor=ndb.Key( urlsafe=conferenceKey)) q = q.filter(ConferenceSession.speaker == speaker) if q.count() > 1: fskey = 'featuredSpeaker-' + conferenceKey memcache.set(fskey, (speaker, [qi.name for qi in q]))
def getConferenceSessionsCreated(self, request): """Return conference sessions 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 = ConferenceSession.query(ancestor=ndb.Key(Profile, user_id)) prof = ndb.Key(Profile, user_id).get() # return set of ConferenceSessionForm objects per ConferenceSession return ConferenceSessionForms( items=[self._copyConferenceSessionToForm(conf) for conf in confs] )
def getConferenceSpeakers(self, request): """Gets all speakers at the desired conference.""" conf = ndb.Key(urlsafe=request.conferenceKey) if conf.kind() != "Conference" or not conf.get(): raise endpoints.NotFoundException( 'No conference found with key: %s' % request.conferenceKey) q = ConferenceSession.query( ancestor=ndb.Key( urlsafe=request.conferenceKey)) q = q.fetch(projection=[ConferenceSession.speaker]) return GetConferenceSpeakersResponse( speakers=list({s.speaker for s in q}) )
def getDaytimeNonWorkshopSessions(self, request): """Get sessions before 7pm and non-worksop""" conf_sess = ConferenceSession.query(ConferenceSession.typeOfSession.IN([ str(SessionType.UNKNOWN), str(SessionType.LECTURE), str(SessionType.KEYNOTE), str(SessionType.MEETUP) ])) no_early_workshop = conf_sess.filter(ConferenceSession.startTime < time(19,00)) if no_early_workshop: # return set of ConferenceSessionForm objects per ConferenceSession return ConferenceSessionForms( items=[self.toConferenceSessionForm(cs) for cs in no_early_workshop] ) else: return ConferenceSessionForms( items=[self.toConferenceSessionForm()] )
def _getFeaturedSpeaker(speaker, websafeConferenceKey): # Check to see if Speaker exists in other sessions in this conference qry1 = ConferenceSession.query() qry2 = qry1.filter(ConferenceSession.speaker == speaker) # Filter on speaker qry3 = qry2.filter(ConferenceSession.websafeConferenceKey == websafeConferenceKey) # Filter on websafeConferenceKey if qry3: # If speaker is in another session in this conference # format sessionSpeakerList and set it in memcache sessionSpeakerList = SESSIONS_TPL % (speaker, ', '.join(conf.name for conf in qry3)) memcache.set(MEMCACHE_SESSIONS_KEY, sessionSpeakerList) else: # If no speaker is in another session in this conference # delete the memcache announcements entry sessionSpeakerList = "" memcache.delete(MEMCACHE_SESSIONS_KEY) return sessionSpeakerList