def _wishlist(self, request, add=True): """ Transaction to add or remove Session from a ConferenceWishlist given by a WishlistRequest :param request: Wishlist RPC Request [VoidMessage, session key in query string] :param add: whether to add (True) to the wishlist or remove from a wishlist (False) :return: BooleanMessage - True if successful, False if failure """ prof = ProfileApi.profile_from_user() # get user Profile session = get_from_webkey(request.websafeSessionKey) # get session if not session or not isinstance(session, Session): raise endpoints.NotFoundException('Not a valid session') # see if the wishlist exists wishlist = ConferenceWishlist().query(ancestor=prof.key) \ .filter(ConferenceWishlist.conferenceKey == session.conferenceKey) \ .get() # User requested to add to the wishlist, so create if needed if not wishlist: if add: # need to create the wishlist first conf_key = session.key.parent() wishlist = ConferenceWishlist(conferenceKey=conf_key, parent=prof.key) else: # remove request, but no wishlist! raise endpoints.NotFoundException( 'Nothing wishlisted for Conference') # update wishlist by adding/removing session key s_key = session.key if s_key not in wishlist.sessionKeys: if add: # add the key wishlist.sessionKeys.append(s_key) wishlist.put() else: # can't remove a nonexistant key raise endpoints.NotFoundException( 'Session not in wishlist for Conference') else: # key already exists if add: # session already wishlisted, so return error return BooleanMessage(data=False) else: # remove key from wishlist wishlist.sessionKeys.remove(s_key) # if wishlist is empty, remove the wishlist. else just update. if len(wishlist.sessionKeys) == 0: wishlist.key.delete() else: wishlist.put() return BooleanMessage(data=True)
def deleteSessionInWishlist(self, request): """Delete the requested session from user's Wishlist.""" # get user Profile profile = self._getProfileFromUser() for session in profile.sessionKeysWishlist: logging.debug(session) if request.websafeSessionKey == session: profile.sessionKeysWishlist.remove(request.websafeSessionKey) profile.put() return BooleanMessage(data=True) else: return BooleanMessage(data=False)
def _register(request, reg=True): """ Register or unregister user for selected conference. :param request: RPC Message Request with a urlsafe Conference Key :param reg: whether to register (True) or unregister (False) the requesting User :return: BooleanMessage - True if successful, False if failure """ prof = ProfileApi.profile_from_user() # get user Profile # check if conf exists given websafeConfKey # get conference; check that it exists c_key = ndb.Key(urlsafe=request.websafeConferenceKey) conf = c_key.get() if not conf: raise endpoints.NotFoundException('No conference found for key') # register if reg: # check if user already registered otherwise add if c_key in prof.conferencesToAttend: raise ConflictException( 'Already registered for this conference') # check if seats avail if conf.seatsAvailable <= 0: raise ConflictException('There are no seats available.') # register user, take away one seat prof.conferencesToAttend.append(c_key) conf.seatsAvailable -= 1 # update datastore prof.put() conf.put() # un-register else: # check if user already registered if c_key in prof.conferencesToAttend: # unregister user, add back one seat prof.conferencesToAttend.remove(c_key) conf.seatsAvailable += 1 # update datastore prof.put() conf.put() else: return BooleanMessage(data=False) return BooleanMessage(data=True)
def delete(self, request): """ Deletes a given Session cleaning up Speakers if needed :param request: :return: """ session = ndb.Key(urlsafe=request.websafeSessionKey).get() if not session: return BooleanMessage(data=False) speakers = ndb.get_multi(session.speakerKeys) return BooleanMessage(data=self._delete(session, speakers))
def updateBalance(self, request): p_key = ndb.Key(UserDetails, request.phoneNumber) result = p_key.get() if not result: return BooleanMessage(data=False) if request.increment == 1: result.balance = result.balance + request.updateAmount result.put() elif request.increment == 0: if result.balance >= request.updateAmount: result.balance = result.balance - request.updateAmount result.put() else: return BooleanMessage(data=False) return BooleanMessage(data=True)
def addFeaturedArticle(self, request): """Add an article to featured articles (Favorites of authorID 0)""" user_author = self._getAuthorFromUser() if not user_author: raise endpoints.UnauthorizedException( '%s is not an author of any articles or comments' % user_author.nickname()) userRights = getattr(UserRights, user_author.userRights) if userRights < UserRights.FELLOW: raise endpoints.ForbiddenException( "Only an administrator or fellow can add a featured article.") self._checkKey(request.websafeArticleKey, 'Article') favoritesAuthor = Author.query(Author.authorID == '0').get() if request.websafeArticleKey in favoritesAuthor.favoriteArticles: raise endpoints.BadRequestException( "Article is already a featured article") favoritesAuthor.favoriteArticles.append(request.websafeArticleKey) favoritesAuthor.put() return BooleanMessage(data=True)
def registerGCM(self, request): p_key = ndb.Key(UserDetails, request.sender) user = p_key.get() succ = 1 if not user: succ = 0 if succ == 1: user.regid = request.regid user.put() if (succ == 0): result = BooleanMessage(data=False) else: result = BooleanMessage(data=True) return result
def _wishlistAdding(self, request, add=True): """Add or delete the session from wishlist""" retval = None prof = self._getProfileFromUser() #get user profile wssk = request.websafeSessionKey session = ndb.Key(urlsafe=wssk).get() if not session: raise endpoints.NotFoundException("No Session found with key: %s" % wssk) wsck = session.confKey if wsck not in prof.conferenceKeysToAttend: raise endpoints.UnauthorizedException( "You should register for the conference") #add to wishlist if add: if wssk in prof.sessionKeysToAdd: raise ConflictException("You have already added this session") prof.sessionKeysToAdd.append(wssk) retval = True else: if wssk in prof.sessionKeysToAdd: prof.sessionKeysToAdd.remove(wssk) retval = True else: retval = False prof.put() return BooleanMessage(data=retval)
def _sessionWishlist(self, request, addTo=True): """Add or remove session from users wishlist. """ retval = None # Fetch user profile prof = self._getProfileFromUser() # Fetch session from websafeSessionKey and check if exists wsck = request.websafeSessionKey sess = ndb.Key(urlsafe=wsck).get() if not sess: raise endpoints.NotFoundException( 'No session found with key: %s' % wsck) # Check if session is already in wishlist otherwise add if addTo: if wsck in prof.wishlistSessionKeys: raise ConflictException( "You have already added this session to your wishlist") prof.wishlistSessionKeys.append(wsck) retval = True # Check if session is in wishlist then remove else: if wsck in prof.wishlistSessionKeys: prof.wishlistSessionKeys.remove(wsck) retval = True else: retval = False # Put back in datastore and return prof.put() return BooleanMessage(data=retval)
def deleteSessionInWishlist(self, request): """Remove Session from user's wishlist list""" is_deleted = False # verify sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get profile profile = self._getProfileFromUser() # get session sess = ndb.Key(urlsafe=request.sessionKey).get() if not sess: raise endpoints.NotFoundException('No Session found with key: %s' % request.sessionKey) # remove session from wishlist if exists then save profile if request.sessionKey in profile.wishList: profile.wishList.remove(request.sessionKey) profile.put() is_deleted = True # is_deleted is true if session was removed return BooleanMessage(data=is_deleted)
def deleteSessionInWishlist(self, request): """Removes the session from the user's list of sessions they are attending""" #boolean value retval = None #check if logged in user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') #grab user profile prof = self._getProfileFromUser() #use webSafeSessionKey to grab session instance wsck = request.websafeSessionKey sess = ndb.Key(urlsafe=wsck).get() #check if session exists if not sess: raise endpoints.NotFoundException('No Session found with key: %s' % wsck) # Check if session is in user's wishlist then delete session from list if wsck in prof.sessionsKeysToAttend: prof.sessionsKeysToAttend.remove(wsck) retval = True prof.put() return BooleanMessage(data=retval)
def _conferenceRegistration(self, request, reg=True): """Register or unregister user for selected conference.""" retval = None # Get user profile prof = self._getProfileFromUser() # Check if conference given in the websafeConferenceKey exists wsck = request.websafeConferenceKey conf = _getEntityByWebsafeKey(wsck, 'Conference') # Register if reg: # Check if user already registered, otherwise add if wsck in prof.conferenceKeysToAttend: raise ConflictException( "You have already registered for this conference.") # Check if seats available if conf.seatsAvailable <= 0: raise ConflictException("There are no seats available.") # Register user, deduct one seat prof.conferenceKeysToAttend.append(wsck) conf.seatsAvailable -= 1 retval = True # Unregister else: # Check if user already registered if wsck in prof.conferenceKeysToAttend: # Unregister user, add back one seat prof.conferenceKeysToAttend.remove(wsck) conf.seatsAvailable += 1 retval = True else: retval = False # Update the datastore and return prof.put() conf.put() return BooleanMessage(data=retval)
def _addToWishlist(self, request, add=True): """Add/remove sessions from user wishlist""" retval = None prof = self._getProfileFromUser() # get user Profile wssk = request.websafeSessionKey session = ndb.Key(urlsafe=wssk).get() if not session: raise endpoints.NotFoundException('No session found with key: %s' % wssk) # Add to wishlist if add: # Check if user already added session to wishlist if wssk in prof.sessionKeysWishlist: raise ConflictException( 'You have already added this session to your wishlist') # Add session to user wishlist prof.sessionKeysWishlist.append(wssk) retval = True # Remove from wishlist else: if wssk in prof.sessionKeysWishlist: prof.sessionKeysWishlist.remove(wssk) retval = True else: retval = False # Write the profile back to the datastore. prof.put() return BooleanMessage(data=retval)
def copyFromArticles(self, request): '''Copies articles and authors from legacy Articles Kind into new Article and Author kinds''' user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') for article in Articles().all(): if '@' not in article.author: author_email = article.author + '@gmail.com' else: author_email = article.author a_key = ndb.Key(Author, author_email) author = a_key.get() # create new Author if not there if not author: author = Author( key=a_key, authorID=str(Author.allocate_ids(size=1)[0]), displayName=author_email.split('@')[0], mainEmail=author_email, ) author.put() self.copyArticlesKind(article, author) return BooleanMessage(data=True)
def removeFeaturedArticle(self, request): """Remove an article from featured articles (Favorites of authorID 0)""" user_author = self._getAuthorFromUser() if not user_author: raise endpoints.UnauthorizedException( '%s is not an author of any articles or comments' % user_author.nickname()) userRights = getattr(UserRights, user_author.userRights) if userRights < UserRights.FELLOW: raise endpoints.ForbiddenException( "Only an administrator or fellow can remove a featured article." ) self._checkKey(request.websafeArticleKey, 'Article') favoritesAuthor = Author.query()\ .filter(Author.authorID=='0')\ .get() if not request.websafeArticleKey in favoritesAuthor.favoriteArticles: raise endpoints.NotFoundException( "Article is not a featured article") # find and delete the article key idx = favoritesAuthor.favoriteArticles.index(request.websafeArticleKey) del favoritesAuthor.favoriteArticles[idx] favoritesAuthor.put() return BooleanMessage(data=True)
def addSessionToWishlist(self, request): """Adds a session to a user's list of sessions they are interested in attending.""" retval = None prof = self._getProfileFromUser() # get user Profile # check if session exists given websafeSessionKey # get session; check that it exists wssk = request.websafeSessionKey sess_key = ndb.Key(urlsafe=wssk) if sess_key.kind() != "Session": raise endpoints.NotFoundException( 'Not a session found with key: %s' % wssk) sess = sess_key.get() if not sess: raise endpoints.NotFoundException('No session found with key: %s' % wssk) # check if user already registered otherwise add if wssk in prof.sessionKeysWishlist: raise ConflictException("You have already added this session") # add to user's wishlist prof.sessionKeysWishlist.append(wssk) retval = True # write things back to the datastore & return prof.put() return BooleanMessage(data=retval)
def _addSessionWishListObject(self, request): """Add Session in WishList, returning True is success otherwise False.""" retval = None # preload necessary data items prof = self._getProfileFromUser() # check if session exists given websafeConfKey # get session; check that it exists wssk = request.websafeSessionKey sess = ndb.Key(urlsafe=wssk).get() if not sess: raise endpoints.NotFoundException('No Session found with key: %s' % wssk) # check if session is already added to wishist otherwise add if wssk in prof.sessionKeysInWishList: raise ConflictException( "This session is already added to your wishlist") # add session in the wishlist if wssk not in prof.sessionKeysInWishList: prof.sessionKeysInWishList.append(wssk) retval = True else: retval = False # write things back to the datastore & return prof.put() return BooleanMessage(data=retval)
def _sessionWishlist(self, request, add=True): """Add or delete a session from a user's wishlist""" profile = self._getProfileFromUser() session_websafekey = request.websafeSessionKey session = ndb.Key(urlsafe=session_websafekey).get() if not session: raise endpoints.NotFoundException( 'No session found with key: %s' % session_websafekey ) if add: if session_websafekey in profile.sessionWishlist: raise ConflictException( "You already have this session in your wishlist" ) else: profile.sessionWishlist.append(session_websafekey) return_value = True else: if session_websafekey in profile.sessionWishlist: profile.sessionWishlist.remove(session_websafekey) return_value = True else: return_value = False profile.put() return BooleanMessage(data=return_value)
def deleteSessionInWishlist(self, request): """Delete session from wishlist (by websafeSessionKey).""" retval = None # preload necessary data items prof = self._getProfileFromUser() # check if session exists given websafeConfKey # get session; check that it exists wssk = request.websafeSessionKey sess = ndb.Key(urlsafe=wssk).get() if not sess: raise endpoints.NotFoundException('No Session found with key: %s' % wssk) # check if session is not in the wishist if wssk not in prof.sessionKeysInWishList: raise ConflictException( "This session is not added to your wishlist") # remove session from the wishlist prof.sessionKeysInWishList.remove(wssk) retval = True # write things back to the datastore & return prof.put() return BooleanMessage(data=retval)
def _sessionRegistration(self, request): """Transaction to register or unregister user for selected session.""" retval = None # get user Profile prof = self._getProfileFromUser() # check if session exists given websafeSessionfKey # get conference; check that it exists wssk = request.websafeSessionKey sess = ndb.Key(urlsafe=wssk).get() if not sess: raise endpoints.NotFoundException( 'No session found with key: %s' % wssk) # check if user already registered otherwise add if wssk in prof.conferenceKeysToAttend: raise ConflictException( "You have already registered for this session") # check if user already registered if wssk in prof.sessionKeysToAttend: retval = False else: # register user to attend session prof.sessionKeysToAttend.append(wssk) retval = True # write things back to the datastore & return prof.put() return BooleanMessage(data=retval)
def addSessionToWishlist(self, request): """ Add a session to the user's wishlist. """ prof = self._getProfileFromUser() session = ndb.Key(urlsafe=request.sessionKey).get() # print "the session's parent is: ", session.parent if not session: raise endpoints.NotFoundException('No session with that key: %s' % request.sessionKey) return BooleanMessage(data=False) if request.sessionKey in prof.session_wish_list: raise ConflictException( "You have already expressed your desire to be at this session!" ) else: prof.session_wish_list.append(request.sessionKey) prof.put() return BooleanMessage(data=True)
def transferAmount(self, request): p_key = ndb.Key(UserDetails, request.sender) send = p_key.get() if not send: return BooleanMessage(data=False) if send.balance < request.amount: return BooleanMessage(data=False) p_key2 = ndb.Key(UserDetails, request.receiver) recv = p_key2.get() if not recv: return BooleanMessage(data=False) send.balance = send.balance - request.amount send.put() recv.balance = recv.balance + request.amount recv.put() return BooleanMessage(data=True)
def deleteAllGames(self, request): """ deleting all Games created by current player, except those that are played. """ # keys_only:All operations return keys instead of entities. ndb.delete_multi(Game.query().fetch(keys_only=True)) deleted = True return BooleanMessage(data=deleted)
def _deleteBook(self, request): book = get_entity_by_websafeKey_key(request.websafeKey) try: book.key.delete() return BooleanMessage(data=True) except Exception, e: raise endpoints.InternalServerErrorException(e.message)
def deleteSessionInWishlist(self, request): """Delete specified session from wishlist""" prof = self._getProfileFromUser() if request.session in prof.sessionWishList: wishlist = prof.sessionWishList index = wishlist.index(request.session) del prof.sessionWishList[index] prof.put() print prof.sessionWishList return BooleanMessage(data=True)
def clearAllData(self,request): """Clear all the data saved.""" ndb.delete_multi(Session.query().fetch(keys_only = True)) ndb.delete_multi(Conference.query().fetch(keys_only = True)) profiles = Profile.query() for profile in profiles: profile.conferenceKeysToAttend = [] profile.sessionKeysInWishlist = [] profile.put() return BooleanMessage(data=True)
def deleteSessionFromWishlist(self, request): """Delete Session from user wishlist.""" prof = self._getProfileFromUser() wssk = request.websafeSessionKey if wssk in prof.sessionsToAttend: prof.sessionsToAttend.remove(wssk) retval = True else: retval = False prof.put() return BooleanMessage(data=retval)
def registerMerchant(self, request): p_key = ndb.Key(MerchantDetails, request.displayName) merchant = MerchantDetails( key=p_key, displayName=request.displayName, balance=request.balance, phoneNumber=request.phoneNumber, pin=request.pin, ) merchant.put() return BooleanMessage(data=True)
def _updateSessionWishlist(self, request, reg=True): """ It updates the wishlist attribute of the profile entity of user. Stores the session keys It adds the session in wishlist if the reg parameter is true, otherwise removes the session from wishlist This method is transactional so that in case of any failure, the partial changes are reverted """ retval = None prof = self._getProfileFromUser() # get user Profile # check if session exists given websafeSessionKey # get session; check that it exists wssk = request.websafeSessionKey session_key = ndb.Key(urlsafe=wssk) # Assure the websafe key is only for Session and raise exception if # key is provided for non Session kind if session_key.kind() != "Session": raise endpoints.NotFoundException( 'wrong websafeSessionKey provided') session = session_key.get() if not session: raise endpoints.NotFoundException( 'No conference found with key: %s' % wssk) # add session to wishlist if reg: # check if user already has the session in wishlist, otherwise add if session_key in prof.sessionsWishList: raise ConflictException( "This session is already in the wishlist") # register user, take away one seat prof.sessionsWishList.append(session_key) retval = True # remove session from wishlist else: # check if session is already in wishlist if session_key in prof.sessionsWishList: # remove session from wishlist prof.sessionsWishList.remove(session_key) retval = True else: retval = False # write things back to the datastore & return prof.put() return BooleanMessage(data=retval)
def deleteSessionInWishlist(self, request): """Get list of sessions that user has interested in.""" # Get user Profile prof = self._getProfileFromUser() # Get session key wsck = request.SessionKey # Remove any empty values in array to protect from type value error if wsck in prof.sessionWishListKeys: prof.sessionWishListKeys.remove(wsck) # Write update back to datastore and return prof.put() return BooleanMessage(data=True)