def post(self, *args, **kwargs): #@UnusedVariable ''' @keyword actor: @keyword deal: @requires: user is the owner of the deal @return: Success @rtype: bool ''' user = kwargs.get('actor') deal = kwargs.get('deal') try: # assure that the user is the owner of the deal assert deal.parent_key() == user.key( ), 'User does not own that deal' # expire the deal without a notification only if active if deal.deal_status == levr.DEAL_STATUS_ACTIVE \ or deal.deal_status == levr.DEAL_STATUS_TEST: deal.expire() deal.put() # otherwise, do nothing. private = True packaged_deal = api_utils.package_deal(deal, private) response = {'deal': packaged_deal} api_utils.send_response(self, response, user) except AssertionError, e: self.send_error(e)
def get(self,*args,**kwargs): ''' Get information about a deal. Input: None Output:{ meta:{ success errorMsg } response:{ <DEAL OBJECT> } } ''' try: logging.debug('DEAL INFO\n\n\n') logging.debug(kwargs) deal = kwargs.get('deal') private = kwargs.get('private') assert deal, 'Deal could not be found' response = { 'deal' : api_utils.package_deal(deal,private) } api_utils.send_response(self,response) except AssertionError,e: levr.log_error(e) api_utils.send_error(self,e.message)
def get(self, identifier): try: logging.debug(identifier) deal = levr.Deal.all().filter('share_id =', identifier).get() if deal: logging.debug(deal) ninjaKey = deal.key().parent() ninja = levr.Customer.get(ninjaKey) #CHANGE THIS: #enc_key = enc.encrypt_key(str(deal.key())) enc_key = enc.encrypt_key(str(deal.key())) template_values = { 'deal': api_utils.package_deal(deal), 'ninja': ninja.display_name, 'lat': deal.geo_point.lat, 'lon': deal.geo_point.lon, 'enc_key': enc_key } logging.debug(template_values) logging.debug(deal.__str__()) template = jinja_environment.get_template( 'templates/share.html') self.response.out.write(template.render(template_values)) else: template = jinja_environment.get_template( 'templates/shareError.html') self.response.out.write(template.render()) except: levr.log_error()
def post(self,*args,**kwargs): #@UnusedVariable ''' @keyword actor: @keyword deal: @requires: user is the owner of the deal @return: Success @rtype: bool ''' user = kwargs.get('actor') deal = kwargs.get('deal') try: # assure that the user is the owner of the deal assert deal.parent_key() == user.key(), 'User does not own that deal' # expire the deal without a notification only if active if deal.deal_status == levr.DEAL_STATUS_ACTIVE \ or deal.deal_status == levr.DEAL_STATUS_TEST: deal.expire() deal.put() # otherwise, do nothing. private = True packaged_deal = api_utils.package_deal(deal, private) response = { 'deal' : packaged_deal } api_utils.send_response(self,response, user) except AssertionError,e: self.send_error(e)
def post(self,*args,**kwargs): #@UnusedVariable ''' @keyword actor: required @keyword deal: required @keyword development: required @requires: user is the owner of the deal @return: success @rtype: Boolean ''' user = kwargs.get('actor') deal = kwargs.get('deal') # development = kwargs.get('development') try: #assure that this user does own the deal assert deal.parent_key() == user.key() deal.reanimate() deal.put() # TODO: this should package all of the deals private = True packaged_deal = api_utils.package_deal(deal, private) response = { 'deal' : packaged_deal } api_utils.send_response(self,response, user) except AssertionError,e: self.send_error(e)
def post(self, *args, **kwargs): #@UnusedVariable ''' @keyword actor: required @keyword deal: required @keyword development: required @requires: user is the owner of the deal @return: success @rtype: Boolean ''' user = kwargs.get('actor') deal = kwargs.get('deal') # development = kwargs.get('development') try: #assure that this user does own the deal assert deal.parent_key() == user.key() deal.reanimate() deal.put() # TODO: this should package all of the deals private = True packaged_deal = api_utils.package_deal(deal, private) response = {'deal': packaged_deal} api_utils.send_response(self, response, user) except AssertionError, e: self.send_error(e)
def get(self, *args, **kwargs): ''' Get information about a deal. Input: None Output:{ meta:{ success errorMsg } response:{ <DEAL OBJECT> } } ''' try: logging.debug('DEAL INFO\n\n\n') logging.debug(kwargs) deal = kwargs.get('deal') private = kwargs.get('private') assert deal, 'Deal could not be found' response = {'deal': api_utils.package_deal(deal, private)} api_utils.send_response(self, response) except AssertionError, e: levr.log_error(e) api_utils.send_error(self, e.message)
def get(self, *args, **kwargs): ''' /user/uid/favorites Get all of a users favorite deals inputs: response:{ numResults: <int> deals: [<deal>,<deal>] } ''' #RESTRICTED try: logging.info("\n\nGET USER FAVORITES") logging.info(kwargs) logging.info(args) user = kwargs.get('user') # uid = user.key() private = kwargs.get('private') limit = kwargs.get('limit') offset = kwargs.get('offset') #grab all favorites favorites = user.favorites #check list is longer than offset if favorites.__len__() > offset: #grab list from offset to end favorites = favorites[offset:] #check list is longer than limit if favorites.__len__() > limit: #there are more favorites than the limit requests so shorten favorites favorites = favorites[:limit] #fetch all favorite entities favorites = levr.Deal.get(favorites) deals = [] #package each deal object for deal in favorites: if deal: deals.append(api_utils.package_deal(deal, False)) else: #favorites is either empty or the offset is past the length of it deals = [] #create response object response = {'numResults': str(favorites.__len__()), 'deals': deals} logging.debug(response) #respond api_utils.send_response(self, response, user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self, *args, **kwargs): try: #grab the content ID contentID = args[0] #contentID = self.request.get('contentID') logging.debug('ContentID: ' + contentID) #uhh wtf do i do? floating_content = levr.FloatingContent.gql( 'WHERE contentID=:1', contentID).get() logging.info(floating_content.action) if floating_content.action == 'upload': user = floating_content.user #write out upload template template = jinja_environment.get_template( 'templates/mobileupload.html') template_values = { 'uid': enc.encrypt_key(str(floating_content.user.key())), 'businessID': enc.encrypt_key(str(floating_content.business.key())), 'upload_url': blobstore.create_upload_url('/mobile/upload') } logging.debug(template_values) # upload_url = blobstore.create_upload_url('/mobile/upload') # # self.response.out.write('<html><body>') # self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) # self.response.out.write('Business ID: <input name="businessID" value="%s">' % enc.encrypt_key(str(floating_content.business.key()))) # self.response.out.write('uid: <input name="uid" value="%s">' % enc.encrypt_key(str(floating_content.user.key()))) # self.response.out.write('''Upload File: <input type="file" name="img"><br> <input type="submit" # name="submit" value="Create!"> </form></body></html>''') elif floating_content.action == 'deal': #write out deal template template = jinja_environment.get_template( 'templates/mobiledealview.html') template_values = { 'uid': enc.encrypt_key(str(floating_content.user.key())), 'deal': api_utils.package_deal(floating_content.deal), 'user_agent': check_user_agent(self) } self.response.out.write(template.render(template_values)) except: levr.log_error()
def get(self,*args,**kwargs): try: #grab the content ID contentID = args[0] #contentID = self.request.get('contentID') logging.debug('ContentID: ' + contentID) #uhh wtf do i do? floating_content = levr.FloatingContent.gql('WHERE contentID=:1',contentID).get() logging.info(floating_content.action) if floating_content.action == 'upload': user = floating_content.user #write out upload template template = jinja_environment.get_template('templates/mobileupload.html') template_values = { 'uid':enc.encrypt_key(str(floating_content.user.key())), 'businessID':enc.encrypt_key(str(floating_content.business.key())), 'upload_url':blobstore.create_upload_url('/mobile/upload') } logging.debug(template_values) # upload_url = blobstore.create_upload_url('/mobile/upload') # # self.response.out.write('<html><body>') # self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) # self.response.out.write('Business ID: <input name="businessID" value="%s">' % enc.encrypt_key(str(floating_content.business.key()))) # self.response.out.write('uid: <input name="uid" value="%s">' % enc.encrypt_key(str(floating_content.user.key()))) # self.response.out.write('''Upload File: <input type="file" name="img"><br> <input type="submit" # name="submit" value="Create!"> </form></body></html>''') elif floating_content.action == 'deal': #write out deal template template = jinja_environment.get_template('templates/mobiledealview.html') template_values = { 'uid':enc.encrypt_key(str(floating_content.user.key())), 'deal': api_utils.package_deal(floating_content.deal), 'user_agent': check_user_agent(self) } self.response.out.write(template.render(template_values)) except: levr.log_error()
def get(self): try: #should only return deals with a foursquare_id set deals = levr.Deal.all().filter('foursquare_id >','').fetch(None) logging.debug('number of foursquare deals: '+str(deals.__len__())) # for deal in deals: # assert deal.foursquare_id, 'A deal was returned that does not have a foursquare id. change the query.' return_deals = [api_utils.package_deal(deal) for deal in deals if deal.foursquare_id] response = { 'foursquareDeals' : return_deals, 'numFoursquareDeals' : return_deals.__len__() } api_utils.send_response(self,response) except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self, *args, **kwargs): ''' Get all of a users uploaded deals inputs: limit(optional), offset(optional) response:{ deal: <DEAL OBJECT> } ''' try: logging.info("\n\nGET USER UPLOADS") logging.debug(kwargs) user = kwargs.get('user') uid = user.key() private = kwargs.get('private') limit = kwargs.get('limit') offset = kwargs.get('offset') #grab all deals that are owned by the specified customer deals = levr.Deal.all().ancestor(uid).fetch(limit, offset=offset) #package up the dealios packaged_deals = [ api_utils.package_deal(deal, private) for deal in deals ] #package the user object packaged_user = api_utils.package_user(user, private) #create response object response = { 'numResults': str(packaged_deals.__len__()), 'deals': packaged_deals, 'user': packaged_user } #respond api_utils.send_response(self, response, user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self): try: #should only return deals with a foursquare_id set deals = levr.Deal.all().filter('foursquare_id >', '').fetch(None) logging.debug('number of foursquare deals: ' + str(deals.__len__())) # for deal in deals: # assert deal.foursquare_id, 'A deal was returned that does not have a foursquare id. change the query.' return_deals = [ api_utils.package_deal(deal) for deal in deals if deal.foursquare_id ] response = { 'foursquareDeals': return_deals, 'numFoursquareDeals': return_deals.__len__() } api_utils.send_response(self, response) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self,*args,**kwargs): ''' Get all of a users uploaded deals inputs: limit(optional), offset(optional) response:{ deal: <DEAL OBJECT> } ''' try: logging.info("\n\nGET USER UPLOADS") logging.debug(kwargs) user = kwargs.get('user') uid = user.key() private = kwargs.get('private') limit = kwargs.get('limit') offset = kwargs.get('offset') #grab all deals that are owned by the specified customer deals = levr.Deal.all().ancestor(uid).fetch(limit,offset=offset) #package up the dealios packaged_deals = [api_utils.package_deal(deal,private) for deal in deals] #package the user object packaged_user = api_utils.package_user(user,private) #create response object response = { 'numResults': str(packaged_deals.__len__()), 'deals' : packaged_deals, 'user' : packaged_user } #respond api_utils.send_response(self,response,user) except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self,*args,**kwargs): try: contentID = args[0] #spoof the contentID #contentID='85ff49d2dcb94b99973c5a2b16c5df36' #grab the associated floating content floating_content = levr.FloatingContent.gql('WHERE contentID=:1',contentID).get() action = floating_content.action response = {'action':action} if action == 'upload': business = floating_content.business assert business, 'Business could not be found' #echo back the business response.update({'business':api_utils.package_business(business)}) elif action == 'deal': deal = floating_content.deal assert deal,'Deal could not be found' #echo bcak the deal packaged_deals = [api_utils.package_deal(deal)] response.update({'deals':packaged_deals}) user = floating_content.user assert user, 'Could not find user' #respond, and include levr_token response.update({'user':api_utils.package_user(user,send_token=True)}) api_utils.send_response(self,response) except AssertionError,e: levr.log_error(e) api_utils.send_error(self,e.message)
def get(self, *args, **kwargs): try: contentID = args[0] #spoof the contentID #contentID='85ff49d2dcb94b99973c5a2b16c5df36' #grab the associated floating content floating_content = levr.FloatingContent.gql( 'WHERE contentID=:1', contentID).get() action = floating_content.action response = {'action': action} if action == 'upload': business = floating_content.business assert business, 'Business could not be found' #echo back the business response.update( {'business': api_utils.package_business(business)}) elif action == 'deal': deal = floating_content.deal assert deal, 'Deal could not be found' #echo bcak the deal packaged_deals = [api_utils.package_deal(deal)] response.update({'deals': packaged_deals}) user = floating_content.user assert user, 'Could not find user' #respond, and include levr_token response.update( {'user': api_utils.package_user(user, send_token=True)}) api_utils.send_response(self, response) except AssertionError, e: levr.log_error(e) api_utils.send_error(self, e.message)
def get(self, *args, **kwargs): try: #if we hit this handler it means that a user has both a levr account, and an account with the external service #we need to figure out which service (via the contentID prefix) #then, we need to figure out if we're dealing with two separate accounts #if so, we need to merge these two accounts and update references (are there any?) #grab and parse contentID to figure out what service the user has previously linked with logging.debug(kwargs) user = kwargs.get('actor') uid = user.key() contentID = kwargs.get('contentID') assert contentID, 'contentID is not being passed' # contentID = args[0] service = contentID[0:3] #grab the floating content and the requesting user floating_content = levr.FloatingContent.gql( 'WHERE contentID=:1', contentID).get() # donor = floating_content.user if service == 'fou': logging.debug('The user came from foursquare') if user.foursquare_connected != True: #add the foursquare information from the donor to the levr user #create an instance of the Foursquare social connection class task_params = { 'uid': uid, 'contentID': contentID, 'service': 'foursquare' } taskqueue.add(url='/tasks/mergeUsersTask', payload=json.dumps(task_params)) elif service == 'fac': logging.debug('The user came from facebook') if user.facbook_connected != True: #merge these two users task_params = { 'uid': uid, 'contentID': contentID, 'service': 'facebook' } taskqueue.add(url='/tasks/mergeUsersTask', payload=json.dumps(task_params)) #merge stuff hereeeee elif service == 'twi': logging.debug('The user came from twitter') if user.twitter_connected != True: #merge these two users task_params = { 'uid': uid, 'contentID': contentID, 'service': 'twitter' } taskqueue.add(url='/tasks/mergeUsersTask', payload=json.dumps(task_params)) #merge stuff hereeeee else: raise Exception('contentID prefix not recognized: ' + service) #now that that fuckery is done with, grab and return the content requested action = floating_content.action response = {'action': action} if action == 'upload': business = floating_content.business assert business, 'Business could not be found' #echo back the business response.update( {'business': api_utils.package_business(business)}) elif action == 'deal': deal = floating_content.deal assert deal, 'Deal could not be found' #echo bcak the deal packaged_deals = [api_utils.package_deal(deal)] response.update({'deals': packaged_deals}) #respond, including the token because why the hell not #response.update({'user':api_utils.package_user(user,send_token=True)}) api_utils.send_response(self, response) except AssertionError, e: levr.log_error(e) api_utils.send_error(self, e.message)
def get(self, dealID, *args, **kwargs): try: logging.debug('UPVOTE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') uid = user.key() deal = kwargs.get('deal') dealID = deal.key() #=================================================================== # Note, if this code changes, you should also change the code in /cronjobs/undeadActivity because it was copied and pasted... #=================================================================== #favorite logging.debug( levr.log_model_props(user, ['upvotes', 'downvotes', 'favorites'])) logging.debug(levr.log_model_props(deal, ['upvotes', 'downvotes'])) if dealID in user.upvotes: logging.debug('flag deal in upvotes') #user is removing the upvote #remove the offending deal from the user upvotes user.upvotes.remove(dealID) #decrement the deal upvotes deal.upvotes -= 1 #do not change the karma of the user who uploaded it #do not remove from favorites #do not remove notification db.put([user, deal]) elif dealID in user.downvotes: logging.debug('flag deal is in downvotes') #remove deal from downvotes user.downvotes.remove(dealID) #decrement the deals downvotes deal.downvotes -= 1 #add deal to upvotes user.upvotes.append(dealID) #increment the number of upvotes deal.upvotes += 1 #add deal to favorites if dealID not in user.favorites: user.favorites.append(dealID) #do not change the karma of the user who uploaded #do not add notification for the ninja db.put([user, deal]) pass else: logging.debug('flag deal not in upvotes or downvotes') # If the deal is in the users favorites, then they upvoted the deal at one point and then # removed that upvote either via another upvote or a downvote, and they are trying to upvote again # At this point, the deal should get its upvote back, but the ninja gets no karma because they do not # lose a karma point when the deal is downloaded if dealID not in user.favorites: #get owner of the deal ninja = levr.Customer.get(deal.key().parent()) #check owner. if the owner is a dummy owner left over from an account transfer, grab the real owner. if ninja.email == '*****@*****.**': logging.debug( '\n\n\n \t\t\t DUMMY NINJA! REDIRECTING REFERENCE TO THE REAL ONE!!! \n\n\n' ) ninja = levr.Customer.get(ninja.pw) #compare owner to user doing the voting if ninja.key() == user.key(): #ninja is upvoting his own deal #increase that users karma! reward for uploading a deal! user.karma += 1 #level check! levr.level_check(user) else: #increase the ninjas karma ninja.karma += 1 #level check! levr.level_check(ninja) #replace ninja. we dont want him anymore ninja.put() #add to upvote list user.upvotes.append(dealID) # #increase the deal upvotes deal.upvotes += 1 #add to users favorites list if not there already if dealID not in user.favorites: user.favorites.append(dealID) #create favorite notification for the ninja that uploaded levr.create_notification('favorite', ninja.key(), uid, dealID) db.put([user, deal]) #put actor and ninja and deal back assert deal, 'Deal was not found' response = {'deal': api_utils.package_deal(deal)} api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error(e) api_utils.send_error(self, e.message)
def get(self, dealID, *args, **kwargs): try: logging.debug('DOWNVOTE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') # uid = user.key() deal = kwargs.get('deal') dealID = deal.key() #favorite logging.debug(levr.log_model_props(user)) if dealID in user.downvotes: logging.debug('flag deal is in downvotes') user.downvotes.remove(dealID) #decrement the deal downvotes deal.downvotes -= 1 #do not change the karma of the user who uploaded it #do not add to favorites #do not create notification db.put([user, deal]) elif dealID in user.upvotes: logging.debug('flag deal is in downvotes') #remove from user upvotes user.upvotes.remove(dealID) #decrement deal upvotes deal.upvotes -= 1 #add to user downvotes user.downvotes.append(dealID) #increment deal downvotes deal.downvotes += 1 #replace entities db.put([user, deal]) else: logging.debug('Flag deal not in upvotes or downvotes') #add to user downvotes user.downvotes.append(dealID) #downvote deal deal.downvotes += 1 #replace entities db.put([user, deal]) assert deal, 'Deal could not be found' response = {'deal': api_utils.package_deal(deal)} api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error() api_utils.send_error(self, e.message)
def get(self,*args,**kwargs): try: #if we hit this handler it means that a user has both a levr account, and an account with the external service #we need to figure out which service (via the contentID prefix) #then, we need to figure out if we're dealing with two separate accounts #if so, we need to merge these two accounts and update references (are there any?) #grab and parse contentID to figure out what service the user has previously linked with logging.debug(kwargs) user = kwargs.get('actor') uid = user.key() contentID = kwargs.get('contentID') assert contentID,'contentID is not being passed' # contentID = args[0] service = contentID[0:3] #grab the floating content and the requesting user floating_content = levr.FloatingContent.gql('WHERE contentID=:1',contentID).get() # donor = floating_content.user if service=='fou': logging.debug('The user came from foursquare') if user.foursquare_connected != True: #add the foursquare information from the donor to the levr user #create an instance of the Foursquare social connection class task_params = { 'uid' : uid, 'contentID' : contentID, 'service' : 'foursquare' } taskqueue.add(url='/tasks/mergeUsersTask',payload=json.dumps(task_params)) elif service=='fac': logging.debug('The user came from facebook') if user.facbook_connected != True: #merge these two users task_params = { 'uid' : uid, 'contentID' : contentID, 'service' : 'facebook' } taskqueue.add(url='/tasks/mergeUsersTask',payload=json.dumps(task_params)) #merge stuff hereeeee elif service=='twi': logging.debug('The user came from twitter') if user.twitter_connected != True: #merge these two users task_params = { 'uid' : uid, 'contentID' : contentID, 'service' : 'twitter' } taskqueue.add(url='/tasks/mergeUsersTask',payload=json.dumps(task_params)) #merge stuff hereeeee else: raise Exception('contentID prefix not recognized: '+service) #now that that fuckery is done with, grab and return the content requested action = floating_content.action response = {'action':action} if action == 'upload': business = floating_content.business assert business, 'Business could not be found' #echo back the business response.update({'business':api_utils.package_business(business)}) elif action == 'deal': deal = floating_content.deal assert deal,'Deal could not be found' #echo bcak the deal packaged_deals = [api_utils.package_deal(deal)] response.update({'deals':packaged_deals}) #respond, including the token because why the hell not #response.update({'user':api_utils.package_user(user,send_token=True)}) api_utils.send_response(self,response) except AssertionError,e: levr.log_error(e) api_utils.send_error(self,e.message)
def post(self, *args, **kwargs): try: logging.info('uploadDeal\n\n\n') logging.info(kwargs) user = kwargs.get('actor') uid = user.key() #make sure than an image is uploaded logging.debug(self.get_uploads()) if self.get_uploads(): #will this work? upload = self.get_uploads()[0] blob_key = upload.key() img_key = blob_key upload_flag = True else: upload_flag = False raise KeyError('Image was not uploaded') params = { 'uid': uid, 'business_name': kwargs.get('businessName'), 'geo_point': kwargs.get('geoPoint'), 'vicinity': kwargs.get('vicinity'), 'types': kwargs.get('types'), 'deal_description': kwargs.get('description'), 'deal_line1': kwargs.get('dealText'), 'distance': kwargs.get('distance'), #is -1 if unknown = double 'shareURL': kwargs.get('shareURL'), 'development': kwargs.get('development'), 'img_key': img_key } #create the deal using the origin specified deal_entity = levr.dealCreate(params, 'phone_new_business', upload_flag) #fire off a task to rotate the image task_params = {'blob_key': str(deal_entity.img.key())} logging.info('Sending this to the task: ' + str(task_params)) taskqueue.add(url=IMAGE_ROTATION_TASK_URL, payload=json.dumps(task_params)) #give the user some karma user.karma += 5 #level check! user = api_utils.level_check(user) user.put() #go notify everyone that should be informed try: levr.create_notification('followedUpload', user.followers, user.key(), deal_entity) except: levr.log_error() #grab deal information for sending back to phone deal = api_utils.package_deal(deal_entity, True) response = {'deal': deal} #=================================================================== # Send notification to founders #=================================================================== try: # approve_link = 'http://www.levr.com/admin/deal/{}/approve'.format(enc.encrypt_key(deal_entity.key())) base_url = 'http://www.levr.com/admin/deal/{}/expiration?daysToExpire='.format( enc.encrypt_key(deal_entity.key())) today_only_link = base_url + '0' one_week_link = base_url + '7' one_month_link = base_url + '30' three_month_link = base_url + '90' six_month_link = base_url + '180' one_year_link = base_url + '360' never_link = base_url + '-1' reject_link = 'http://www.levr.com/admin/deal/{}/reject'.format( enc.encrypt_key(deal_entity.key())) message = mail.AdminEmailMessage() message.sender = '*****@*****.**' message.subject = 'New Upload' message.html = '<img src="{}"><br>'.format( deal.get('smallImg')) message.html += '<h2>{}</h2>'.format(deal_entity.deal_text) message.html += '<h3>{}</h3>'.format(deal_entity.description) message.html += '<h4>Uploaded by: {}</h4>'.format( user.display_name) message.html += '<h5>deal_status: {}</h5>'.format( deal_entity.deal_status) message.html += '<br/><p>Set deal expiration.</p>' message.html += '<br><a href="{}">Reject</a><br><br>'.format( reject_link) message.html += '<br><a href="{}">Today Only</a><br><br>'.format( today_only_link) message.html += '<br><a href="{}">One Week</a><br><br>'.format( one_week_link) message.html += '<br><a href="{}">One Month</a><br><br>'.format( one_month_link) message.html += '<br><a href="{}">Three Month</a><br><br>'.format( three_month_link) message.html += '<br><a href="{}">Six Month</a><br><br>'.format( six_month_link) message.html += '<br><a href="{}">One Year</a><br><br>'.format( one_year_link) message.html += '<br><a href="{}">Forever!!!</a><br><br>'.format( never_link) message.html += levr.log_dict(deal, None, '<br>') # message.body += '\n\n\n\n\n\nApprove: {}'.format(approve_link) message.check_initialized() message.send() except: levr.log_error() api_utils.send_response(self, response) except KeyError, e: logging.info('Key Error') logging.info(str(e)) levr.log_error() api_utils.send_error(self, str(e))
def get(self,*args,**kwargs): ''' /user/uid/favorites Get all of a users favorite deals inputs: response:{ numResults: <int> deals: [<deal>,<deal>] } ''' #RESTRICTED try: logging.info("\n\nGET USER FAVORITES") logging.info(kwargs) logging.info(args) user = kwargs.get('user') # uid = user.key() private = kwargs.get('private') limit = kwargs.get('limit') offset = kwargs.get('offset') #grab all favorites favorites = user.favorites #check list is longer than offset if favorites.__len__() > offset: #grab list from offset to end favorites = favorites[offset:] #check list is longer than limit if favorites.__len__() > limit: #there are more favorites than the limit requests so shorten favorites favorites = favorites[:limit] #fetch all favorite entities favorites = levr.Deal.get(favorites) deals = [] #package each deal object for deal in favorites: if deal: deals.append(api_utils.package_deal(deal,False)) else: #favorites is either empty or the offset is past the length of it deals = [] #create response object response = { 'numResults': str(favorites.__len__()), 'deals' : deals } logging.debug(response) #respond api_utils.send_response(self,response,user) except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self,dealID,*args,**kwargs): try: logging.debug('DOWNVOTE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') # uid = user.key() deal = kwargs.get('deal') dealID = deal.key() #favorite logging.debug(levr.log_model_props(user)) if dealID in user.downvotes: logging.debug('flag deal is in downvotes') user.downvotes.remove(dealID) #decrement the deal downvotes deal.downvotes -= 1 #do not change the karma of the user who uploaded it #do not add to favorites #do not create notification db.put([user,deal]) elif dealID in user.upvotes: logging.debug('flag deal is in downvotes') #remove from user upvotes user.upvotes.remove(dealID) #decrement deal upvotes deal.upvotes -= 1 #add to user downvotes user.downvotes.append(dealID) #increment deal downvotes deal.downvotes += 1 #replace entities db.put([user,deal]) else: logging.debug('Flag deal not in upvotes or downvotes') #add to user downvotes user.downvotes.append(dealID) #downvote deal deal.downvotes += 1 #replace entities db.put([user,deal]) assert deal,'Deal could not be found' response = { 'deal':api_utils.package_deal(deal) } api_utils.send_response(self,response,user) except AssertionError,e: levr.log_error() api_utils.send_error(self,e.message)
def get(self,dealID,*args,**kwargs): try: logging.debug('UPVOTE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') uid = user.key() deal = kwargs.get('deal') dealID = deal.key() #=================================================================== # Note, if this code changes, you should also change the code in /cronjobs/undeadActivity because it was copied and pasted... #=================================================================== #favorite logging.debug(levr.log_model_props(user,['upvotes','downvotes','favorites'])) logging.debug(levr.log_model_props(deal,['upvotes','downvotes'])) if dealID in user.upvotes: logging.debug('flag deal in upvotes') #user is removing the upvote #remove the offending deal from the user upvotes user.upvotes.remove(dealID) #decrement the deal upvotes deal.upvotes -= 1 #do not change the karma of the user who uploaded it #do not remove from favorites #do not remove notification db.put([user,deal]) elif dealID in user.downvotes: logging.debug('flag deal is in downvotes') #remove deal from downvotes user.downvotes.remove(dealID) #decrement the deals downvotes deal.downvotes -= 1 #add deal to upvotes user.upvotes.append(dealID) #increment the number of upvotes deal.upvotes += 1 #add deal to favorites if dealID not in user.favorites: user.favorites.append(dealID) #do not change the karma of the user who uploaded #do not add notification for the ninja db.put([user,deal]) pass else: logging.debug('flag deal not in upvotes or downvotes') # If the deal is in the users favorites, then they upvoted the deal at one point and then # removed that upvote either via another upvote or a downvote, and they are trying to upvote again # At this point, the deal should get its upvote back, but the ninja gets no karma because they do not # lose a karma point when the deal is downloaded if dealID not in user.favorites: #get owner of the deal ninja = levr.Customer.get(deal.key().parent()) #check owner. if the owner is a dummy owner left over from an account transfer, grab the real owner. if ninja.email == '*****@*****.**': logging.debug('\n\n\n \t\t\t DUMMY NINJA! REDIRECTING REFERENCE TO THE REAL ONE!!! \n\n\n') ninja = levr.Customer.get(ninja.pw) #compare owner to user doing the voting if ninja.key() == user.key(): #ninja is upvoting his own deal #increase that users karma! reward for uploading a deal! user.karma += 1 #level check! levr.level_check(user) else: #increase the ninjas karma ninja.karma += 1 #level check! levr.level_check(ninja) #replace ninja. we dont want him anymore ninja.put() #add to upvote list user.upvotes.append(dealID) # #increase the deal upvotes deal.upvotes += 1 #add to users favorites list if not there already if dealID not in user.favorites: user.favorites.append(dealID) #create favorite notification for the ninja that uploaded levr.create_notification('favorite',ninja.key(),uid,dealID) db.put([user,deal]) #put actor and ninja and deal back assert deal, 'Deal was not found' response = { 'deal':api_utils.package_deal(deal) } api_utils.send_response(self,response,user) except AssertionError,e: levr.log_error(e) api_utils.send_error(self,e.message)
def post(self, *args, **kwargs): try: logging.info("uploadDeal\n\n\n") logging.info(kwargs) user = kwargs.get("actor") uid = user.key() # make sure than an image is uploaded logging.debug(self.get_uploads()) if self.get_uploads(): # will this work? upload = self.get_uploads()[0] blob_key = upload.key() img_key = blob_key upload_flag = True else: upload_flag = False raise KeyError("Image was not uploaded") params = { "uid": uid, "business_name": kwargs.get("businessName"), "geo_point": kwargs.get("geoPoint"), "vicinity": kwargs.get("vicinity"), "types": kwargs.get("types"), "deal_description": kwargs.get("description"), "deal_line1": kwargs.get("dealText"), "distance": kwargs.get("distance"), # is -1 if unknown = double "shareURL": kwargs.get("shareURL"), "development": kwargs.get("development"), "img_key": img_key, } # create the deal using the origin specified deal_entity = levr.dealCreate(params, "phone_new_business", upload_flag) # fire off a task to rotate the image task_params = {"blob_key": str(deal_entity.img.key())} logging.info("Sending this to the task: " + str(task_params)) taskqueue.add(url=IMAGE_ROTATION_TASK_URL, payload=json.dumps(task_params)) # give the user some karma user.karma += 5 # level check! user = api_utils.level_check(user) user.put() # go notify everyone that should be informed try: levr.create_notification("followedUpload", user.followers, user.key(), deal_entity) except: levr.log_error() # grab deal information for sending back to phone deal = api_utils.package_deal(deal_entity, True) response = {"deal": deal} # =================================================================== # Send notification to founders # =================================================================== try: # approve_link = 'http://www.levr.com/admin/deal/{}/approve'.format(enc.encrypt_key(deal_entity.key())) base_url = "http://www.levr.com/admin/deal/{}/expiration?daysToExpire=".format( enc.encrypt_key(deal_entity.key()) ) today_only_link = base_url + "0" one_week_link = base_url + "7" one_month_link = base_url + "30" three_month_link = base_url + "90" six_month_link = base_url + "180" one_year_link = base_url + "360" never_link = base_url + "-1" reject_link = "http://www.levr.com/admin/deal/{}/reject".format(enc.encrypt_key(deal_entity.key())) message = mail.AdminEmailMessage() message.sender = "*****@*****.**" message.subject = "New Upload" message.html = '<img src="{}"><br>'.format(deal.get("smallImg")) message.html += "<h2>{}</h2>".format(deal_entity.deal_text) message.html += "<h3>{}</h3>".format(deal_entity.description) message.html += "<h4>Uploaded by: {}</h4>".format(user.display_name) message.html += "<h5>deal_status: {}</h5>".format(deal_entity.deal_status) message.html += "<br/><p>Set deal expiration.</p>" message.html += '<br><a href="{}">Reject</a><br><br>'.format(reject_link) message.html += '<br><a href="{}">Today Only</a><br><br>'.format(today_only_link) message.html += '<br><a href="{}">One Week</a><br><br>'.format(one_week_link) message.html += '<br><a href="{}">One Month</a><br><br>'.format(one_month_link) message.html += '<br><a href="{}">Three Month</a><br><br>'.format(three_month_link) message.html += '<br><a href="{}">Six Month</a><br><br>'.format(six_month_link) message.html += '<br><a href="{}">One Year</a><br><br>'.format(one_year_link) message.html += '<br><a href="{}">Forever!!!</a><br><br>'.format(never_link) message.html += levr.log_dict(deal, None, "<br>") # message.body += '\n\n\n\n\n\nApprove: {}'.format(approve_link) message.check_initialized() message.send() except: levr.log_error() api_utils.send_response(self, response) except KeyError, e: logging.info("Key Error") logging.info(str(e)) levr.log_error() api_utils.send_error(self, str(e))