def get(self, *args, **kwargs): ''' #PARTIALLY RESTRICTED inputs: Output:{ meta:{ success errorMsg } response:{ <USER OBJECT> } ''' try: logging.debug('USER INFO\n\n') user = kwargs.get('user') private = kwargs.get('private') #create response object response = {'user': api_utils.package_user(user, private)} #respond api_utils.send_response(self, response, user) except: levr.log_error(self.request) api_utils.send_error(self, 'Server Error')
def get(self,*args,**kwargs): try: logging.info('Reporting for dudty, Captain') #grabthe user from the input user = kwargs.get('actor') try: data = api_utils.SpoofUndeadNinjaActivity(user).run() logging.debug(levr.log_dict(data)) #set last login user = data['user'] except: levr.log_error() user.date_last_login = datetime.now() # logging.debug(user.date_last_login) user.put() response = {'user':api_utils.package_user(user,True)} api_utils.send_response(self,response,user) except: levr.log_error() api_utils.send_error(self,'Server Error')
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): businessID = self.request.get('businessID') if businessID == '': api_utils.send_error(self,'Required parameter not passed: businessID') return #decrypt uid try: businessID = db.Key(enc.decrypt_key(businessID)) except: api_utils.send_error(self,'Invalid parameter: businessID') return #grab the business # business = levr.Business.get(businessID) #call the business #twilio credentials sid = 'AC4880dbd1ff355288728be2c5f5f7406b' token = 'ea7cce49e3bb805b04d00f76253f9f2b' twiliourl='https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/Calls.json' auth_header = 'Basic '+base64.b64encode(sid+':'+token) logging.info(auth_header) request = {'From':'+16173608582', 'To':'+16052610083', 'Url':'http://www.levr.com/api/merchant/twilioanswer', 'StatusCallback':'http://www.levr.com/api/merchant/twiliocallback'} result = urlfetch.fetch(url=twiliourl, payload=urllib.urlencode(request), method=urlfetch.POST, headers={'Authorization':auth_header}) logging.info(levr.log_dict(result.__dict__))
def get(self,*args,**kwargs): ''' Input: uid response: {} ''' try: logging.debug('DELETE FAVORITE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') deal = kwargs.get('deal') # uid = user.key() dealID = deal.key() #if the deal is in the users favorites, remove it. else do nothing if dealID in user.favorites: user.favorites.remove(dealID) #replace entities db.put(user) response = {} api_utils.send_response(self,response,user) except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self, *args, **kwargs): try: logging.info('fetchUploadURL\n\n\n') logging.debug(kwargs) user = kwargs.get('user') #create blobstore user upload_url = blobstore.create_upload_url('/api/upload/post') logging.debug(upload_url) if os.environ['SERVER_SOFTWARE'].startswith('Development') == True: #we are on the development environment URL = 'http://0.0.0.0:8080/' else: #we are deployed on the server URL = 'levr.com/' #create share url share_url = URL + levr.create_unique_id() response = {'uploadURL': upload_url, 'shareURL': share_url} api_utils.send_response(self, response, user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self, *args, **kwargs): ''' Input: uid response: {} ''' try: logging.debug('DELETE FAVORITE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') deal = kwargs.get('deal') # uid = user.key() dealID = deal.key() #if the deal is in the users favorites, remove it. else do nothing if dealID in user.favorites: user.favorites.remove(dealID) #replace entities db.put(user) response = {} api_utils.send_response(self, response, user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self,*args,**kwargs): ''' #PARTIALLY RESTRICTED inputs: Output:{ meta:{ success errorMsg } response:{ <USER OBJECT> } ''' try: logging.debug('USER INFO\n\n') user = kwargs.get('user') private = kwargs.get('private') #create response object response = { 'user' : api_utils.package_user(user,private) } #respond api_utils.send_response(self,response,user) except: levr.log_error(self.request) api_utils.send_error(self,'Server Error')
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): try: logging.info("fetchUploadURL\n\n\n") logging.debug(kwargs) user = kwargs.get("user") # create blobstore user upload_url = blobstore.create_upload_url("/api/upload/post") logging.debug(upload_url) if os.environ["SERVER_SOFTWARE"].startswith("Development") == True: # we are on the development environment URL = "http://0.0.0.0:8080/" else: # we are deployed on the server URL = "levr.com/" # create share url share_url = URL + levr.create_unique_id() response = {"uploadURL": upload_url, "shareURL": share_url} api_utils.send_response(self, response, user) except: levr.log_error() api_utils.send_error(self, "Server Error")
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): ''' Input: uid ''' try: logging.debug("REPORT\n\n\n") logging.debug(kwargs) user = kwargs.get('actor') deal = kwargs.get('deal') uid = user.key() dealID = deal.key() #create report Entity levr.ReportedDeal(uid=uid, dealID=dealID).put() #is it a foursquare deal that got reported? if deal.origin == 'foursquare': #get the business business = levr.Business.get(deal.businessID) #get the business' foursquare ID foursquare_id = business.foursquare_id #is the user a foursquare user? if user.foursquare_token > '': token = user.foursquare_token else: token = 'random' #fire off a task to review the foursquare deals for this business task_params = { 'foursquare_id': foursquare_id, 'token': token, 'deal_id': str(deal.key()), 'uid': str(user.key()), 'deal_status': deal.deal_status } taskqueue.add(url='/tasks/foursquareDealUpdateTask', payload=json.dumps(task_params)) #send notification via email message = mail.EmailMessage( sender="LEVR AUTOMATED <*****@*****.**>", subject="New Reported Deal", to="*****@*****.**") logging.debug(message) body = 'New Reported Deal\n\n' body += levr.log_model_props(user, ['email', 'display_name', '']) body += str(user.email) + ' is reporting ' + str(deal.deal_text) message.body = body logging.debug(message.body) message.send() api_utils.send_response(self, {}, user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self, *args, **kwargs): ''' A user logs in with levr using an email or alias, and a password ''' try: #RESTRICTED logging.debug('LOGIN LEVR\n\n\n') logging.debug(kwargs) email_or_owner = kwargs.get('email_or_owner') pw = kwargs.get('pw') pw = enc.encrypt_password(pw) #check both email and password r_email = levr.Customer.gql('WHERE email = :1 AND pw=:2', email_or_owner, pw).get() r_alias = levr.Customer.gql('WHERE alias = :1 AND pw=:2', email_or_owner, pw).get() if r_email: #match based on email existing_user = r_email elif r_alias: #match based on alias existing_user = r_alias else: api_utils.send_error(self, 'Authentication failed.') return #create or refresh the alias existing_user = levr.build_display_name(existing_user) #=================================================================== # Spoof Ninja Activity! #=================================================================== data = api_utils.SpoofUndeadNinjaActivity(existing_user).run() logging.debug(levr.log_dict(data)) #set last login existing_user = data['user'] #still here? update last login by putting existing_user.put() #package user, private setting, send token response = { 'user': api_utils.package_user(existing_user, True, send_token=True) } api_utils.send_response(self, response, existing_user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self,*args,**kwargs): ''' A user logs in with levr using an email or alias, and a password ''' try: #RESTRICTED logging.debug('LOGIN LEVR\n\n\n') logging.debug(kwargs) email_or_owner = kwargs.get('email_or_owner') pw = kwargs.get('pw') pw = enc.encrypt_password(pw) #check both email and password r_email = levr.Customer.gql('WHERE email = :1 AND pw=:2',email_or_owner,pw).get() r_alias = levr.Customer.gql('WHERE alias = :1 AND pw=:2',email_or_owner,pw).get() if r_email: #match based on email existing_user = r_email elif r_alias: #match based on alias existing_user = r_alias else: api_utils.send_error(self,'Authentication failed.') return #create or refresh the alias existing_user = levr.build_display_name(existing_user) #=================================================================== # Spoof Ninja Activity! #=================================================================== data = api_utils.SpoofUndeadNinjaActivity(existing_user).run() logging.debug(levr.log_dict(data)) #set last login existing_user = data['user'] #still here? update last login by putting existing_user.put() #package user, private setting, send token response = {'user':api_utils.package_user(existing_user,True,send_token=True)} api_utils.send_response(self,response,existing_user) except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self,*args,**kwargs): ''' A user (specified in ?uid=USER_ID) stops following the user specified in (/api/USER_ID/follow) If the user is not a follower and they request to unfollow, then nothing happens and success is true inputs: followerID(required) Output:{ meta:{ success errorMsg } ''' try: logging.info('\n\nUSER REMOVE FOLLOWER') logging.debug(kwargs) user = kwargs.get('user') # uid = user.key() actor = kwargs.get('actor') actorID = actor.key() private = kwargs.get('private') #PERFORM ACTIONS #grab a list of existing followers old_followers = user.followers logging.debug(old_followers) #check if in list of existing followers if actorID in old_followers: logging.debug('Follower exists') #create new list of followers that excludes the requested id new_followers = [u for u in old_followers if u != actorID] logging.debug(new_followers) #replace list of followers user.followers = new_followers #replace user that lost a follower db.put(user) else: logging.debug('follower does not exist. Do nothing') #respond api_utils.send_response(self,{},actor) except: levr.log_error() api_utils.send_error(self,'Server Error')
class ConnectFacebookHandler(webapp2.RequestHandler): @api_utils.validate(None, 'param', user=True, remoteToken=True, levrToken=True) @api_utils.private def post(self, *args, **kwargs): try: #RESTRICTED user = kwargs.get('actor', None) facebook_token = kwargs.get('remoteToken', None) user = social.Facebook(user, 'verbose') try: user, new_user_details, new_friends = user.first_time_connect( facebook_token=facebook_token, ) except Exception, e: levr.log_error() assert False, 'Could not connect with facebook.' logging.debug(levr.log_model_props(user)) logging.debug(str(new_user_details)) #return the user response = { 'user': api_utils.package_user(user, True), 'new_friends': [enc.encrypt_key(f) for f in new_friends], 'new_user_details': new_user_details } api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error() api_utils.send_error(self, '{}'.format(e.message))
def get(self, *args, **kwargs): ''' A user (specified in ?uid=USER_ID) stops following the user specified in (/api/USER_ID/follow) If the user is not a follower and they request to unfollow, then nothing happens and success is true inputs: followerID(required) Output:{ meta:{ success errorMsg } ''' try: logging.info('\n\nUSER REMOVE FOLLOWER') logging.debug(kwargs) user = kwargs.get('user') # uid = user.key() actor = kwargs.get('actor') actorID = actor.key() private = kwargs.get('private') #PERFORM ACTIONS #grab a list of existing followers old_followers = user.followers logging.debug(old_followers) #check if in list of existing followers if actorID in old_followers: logging.debug('Follower exists') #create new list of followers that excludes the requested id new_followers = [u for u in old_followers if u != actorID] logging.debug(new_followers) #replace list of followers user.followers = new_followers #replace user that lost a follower db.put(user) else: logging.debug('follower does not exist. Do nothing') #respond api_utils.send_response(self, {}, actor) except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self, *args, **kwargs): ''' #RESTRICTED inputs: limit,offset,since response:{ numResults : <int> notifications:[ <NOTIFICATION OBJECT> ] } ''' try: logging.info('NOTIFICATIONS\n\n\n') logging.debug('NOTIFICATIONS\n\n\n') logging.debug(kwargs) user = kwargs.get('user') private = kwargs.get('private') sinceDate = kwargs.get('since') logging.debug('sinceDate: ' + str(sinceDate)) logging.debug('last notified: ' + str(user.last_notified)) #get notifications notifications = user.get_notifications(sinceDate) logging.debug('notifications: ' + str(notifications.__len__())) #package up the notifications packaged_notifications = [ api_utils.package_notification(n) for n in notifications ] response = { 'numResults': packaged_notifications.__len__(), 'notifications': packaged_notifications } api_utils.send_response(self, response) # logging.debug(notes) #replace user #!!!!!!!IMPORTANT!!!! user.put() except: levr.log_error() api_utils.send_error(self, 'Server Error')
def get(self,*args,**kwargs): #@UnusedVariable ''' inputs: lat,lon,limit Output:{ meta:{ success errorMsg } response:{ [string,string] } ''' try: pass except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self,*args,**kwargs): ''' #RESTRICTED inputs: limit,offset,since response:{ numResults : <int> notifications:[ <NOTIFICATION OBJECT> ] } ''' try: logging.info('NOTIFICATIONS\n\n\n') logging.debug('NOTIFICATIONS\n\n\n') logging.debug(kwargs) user = kwargs.get('user') private = kwargs.get('private') sinceDate = kwargs.get('since') logging.debug('sinceDate: '+str(sinceDate)) logging.debug('last notified: '+str(user.last_notified)) #get notifications notifications = user.get_notifications(sinceDate) logging.debug('notifications: '+str(notifications.__len__())) #package up the notifications packaged_notifications = [api_utils.package_notification(n) for n in notifications] response = { 'numResults' : packaged_notifications.__len__(), 'notifications' : packaged_notifications } api_utils.send_response(self,response) # logging.debug(notes) #replace user #!!!!!!!IMPORTANT!!!! user.put() except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self, *args, **kwargs): #@UnusedVariable ''' inputs: lat,lon,limit Output:{ meta:{ success errorMsg } response:{ [string,string] } ''' try: pass except: levr.log_error() api_utils.send_error(self, 'Server Error')
class ConnectFoursquareHandler(webapp2.RequestHandler): @api_utils.validate(None, 'param', user=True, remoteToken=True, levrToken=True) #id=True @api_utils.private def post(self, *args, **kwargs): try: #RESTRICTED logging.debug('CONNECT FOURSQUARE\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') foursquare_token = kwargs.get('remoteToken') new_user_details = None new_friends = None #=================================================================== # Check to see if there are multiple accounts # i.e. the user that is connecting w/ foursquare has an existing fs account with levr #=================================================================== # check for an existing foursquare user foursquare_user = levr.Customer.all().filter( 'foursquare_token', foursquare_token).get() # If a user was found in the db with the requested foursquare credentials, # and that user is not the same user as the one requesting the connection, # merge the foursquare created account into the requesting user (i.e. the levr account user) if foursquare_user and foursquare_user is not user: #this means the user has multiple accounts that need to be merged data = api_utils.merge_customer_info_from_B_into_A( user, foursquare_user, 'foursquare') user = data[0] # Otherwise, act normally. Simply connect. If the user already has foursquare credentials, # this will refresh their foursquare information else: #create an instance of the Foursquare social connection class user = social.Foursquare(user, 'verbose') try: user, new_user_details, new_friends = user.first_time_connect( foursquare_token=foursquare_token) except Exception, e: levr.log_error() assert False, 'Could not connect with foursquare. '.format( '') response = { 'user': api_utils.package_user(user, True) # 'new_friends' : [enc.encrypt_key(f) for f in new_friends], # 'new_user_details' : new_user_details } if new_user_details: response['new_user_details'] = new_user_details if new_friends: response['new_friends'] = new_friends api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error() api_utils.send_error(self, '{}'.format(e.message))
def get(self, *args, **kwargs): #@UnusedVariable ''' inputs: lat,lon,limit,radius Output:{ meta:{ success errorMsg } response:{ [string,string] } ''' try: logging.info("\n\nSEARCH NEW") except: levr.log_error() api_utils.send_error(self, 'Server Error')
class SignupTwitterHandler(webapp2.RequestHandler): @api_utils.validate(None, None, remoteID=True, remoteToken=True, remoteTokenSecret=True) def post(self, *args, **kwargs): try: twitter_id = kwargs.get('remoteID', None) twitter_token = kwargs.get('remoteToken', None) twitter_token_secret = kwargs.get('remoteTokenSecret', None) logging.debug('\n\n{}\n{}\n{}\n\n'.format(twitter_id, twitter_token, twitter_token_secret)) user = levr.Customer.all().filter('twitter_id', twitter_id).get() logging.debug(user) if user: #fallback to login logging.debug('User exists!') response = { 'user': api_utils.package_user(user, True, send_token=True) } else: #create new user user = social.Twitter(twitter_id=twitter_id) try: user, new_user_details, new_friends = user.first_time_connect( twitter_id=twitter_id, twitter_token=twitter_token, twitter_token_secret=twitter_token_secret) except Exception, e: levr.log_error() assert False, 'Could not connect with twitter. '.format('') #return the user response = { 'user': api_utils.package_user(user, True, send_token=True), 'new_friends': [enc.encrypt_key(f) for f in new_friends], 'new_user_details': new_user_details } try: if user.display_name == 'Jason K.': from google.appengine.api import mail mail.send_mail(sender="*****@*****.**", to="*****@*****.**", subject="Signup", body='Jason signed up') else: levr.text_notify(user.display_name + ' from Twitter!') except: levr.log_error() api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error() api_utils.send_error(self, '{}'.format(e))
def get(self,*args,**kwargs): #@UnusedVariable ''' inputs: lat,lon,limit,radius Output:{ meta:{ success errorMsg } response:{ [string,string] } ''' try: logging.info("\n\nSEARCH NEW") except: levr.log_error() api_utils.send_error(self,'Server Error')
def get(self, *args, **kwargs): ''' Get all of a users followers #RESTRICTED inputs: Output:{ meta:{ success errorMsg } response:{ followers:[ <USER OBJECT> ] } ''' try: logging.info('GET USER FOLLOWERS\n\n\n') logging.debug(kwargs) user = kwargs.get('user') # uid = user.key() private = kwargs.get('private') # limit = kwargs.get('limit') # offset = kwargs.get('offset') #PERFORM ACTIONS #package each follower into <USER OBJECT> followers = [ api_utils.package_user(u) for u in levr.Customer.get(user.followers) ] logging.debug(followers) response = { 'numResults': followers.__len__(), 'followers': followers } #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 followers #RESTRICTED inputs: Output:{ meta:{ success errorMsg } response:{ followers:[ <USER OBJECT> ] } ''' try: logging.info('GET USER FOLLOWERS\n\n\n') logging.debug(kwargs) user = kwargs.get('user') # uid = user.key() private = kwargs.get('private') # limit = kwargs.get('limit') # offset = kwargs.get('offset') #PERFORM ACTIONS #package each follower into <USER OBJECT> followers = [api_utils.package_user(u) for u in levr.Customer.get(user.followers)] logging.debug(followers) response = { 'numResults' : followers.__len__(), 'followers' : followers } #respond api_utils.send_response(self,response,user) 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): businessID = self.request.get('businessID') if businessID == '': api_utils.send_error(self, 'Required parameter not passed: businessID') return #decrypt uid try: businessID = db.Key(enc.decrypt_key(businessID)) except: api_utils.send_error(self, 'Invalid parameter: businessID') return #grab the business # business = levr.Business.get(businessID) #call the business #twilio credentials sid = 'AC4880dbd1ff355288728be2c5f5f7406b' token = 'ea7cce49e3bb805b04d00f76253f9f2b' twiliourl = 'https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/Calls.json' auth_header = 'Basic ' + base64.b64encode(sid + ':' + token) logging.info(auth_header) request = { 'From': '+16173608582', 'To': '+16052610083', 'Url': 'http://www.levr.com/api/merchant/twilioanswer', 'StatusCallback': 'http://www.levr.com/api/merchant/twiliocallback' } result = urlfetch.fetch(url=twiliourl, payload=urllib.urlencode(request), method=urlfetch.POST, headers={'Authorization': auth_header}) logging.info(levr.log_dict(result.__dict__))
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): ''' A user (specified in ?uid=USER_ID) follows the user specified in (/api/USER_ID/follow) inputs: uid(required) Response:{ None } ''' try: logging.info('\n\n\n\t\t\t USER ADD FOLLOWER\n\n\n') user = kwargs.get('user') # uid = user.key() actor = kwargs.get('actor') actorID = actor.key() private = kwargs.get('private') #add actor to the list of followers if actorID not in user.followers: user.followers.append(actorID) #PERFORM ACTIONS if not levr.create_notification('newFollower', user.key(), actorID): api_utils.send_error(self, 'Server Error') return #get notifications db.put([user, actor]) #respond api_utils.send_response(self, {'dt': str(actor.date_last_notified)}, actor) 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): try: logging.info('Reporting for dudty, Captain') #grabthe user from the input user = kwargs.get('actor') try: data = api_utils.SpoofUndeadNinjaActivity(user).run() logging.debug(levr.log_dict(data)) #set last login user = data['user'] except: levr.log_error() user.date_last_login = datetime.now() # logging.debug(user.date_last_login) user.put() response = {'user': api_utils.package_user(user, True)} 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): ''' A user (specified in ?uid=USER_ID) follows the user specified in (/api/USER_ID/follow) inputs: uid(required) Response:{ None } ''' try: logging.info('\n\n\n\t\t\t USER ADD FOLLOWER\n\n\n') user = kwargs.get('user') # uid = user.key() actor = kwargs.get('actor') actorID = actor.key() private = kwargs.get('private') #add actor to the list of followers if actorID not in user.followers: user.followers.append(actorID) #PERFORM ACTIONS if not levr.create_notification('newFollower',user.key(),actorID): api_utils.send_error(self,'Server Error') return #get notifications db.put([user,actor]) #respond api_utils.send_response(self,{'dt':str(actor.date_last_notified)},actor) except: levr.log_error() api_utils.send_error(self,'Server Error')
class SignupFoursquareHandler(webapp2.RequestHandler): @api_utils.validate(None, None, remoteToken=True) def post(self, *args, **kwargs): try: #check token foursquare_token = kwargs.get('remoteToken', None) user = levr.Customer.all().filter('foursquare_token', foursquare_token).get() if user: #fallback to login response = { 'user': api_utils.package_user(user, True, send_token=True) } else: #=============================================================== # NOTE: there is a remote chance that the users foursquare oauth_token would change. # this would not recognize that #=============================================================== try: #create new user user = social.Foursquare(foursquare_token=foursquare_token) user, new_user_details, new_friends = user.first_time_connect( foursquare_token=foursquare_token, ) except Exception, e: levr.log_error() assert False, 'Could not connect with foursquare. '.format( '') #return the user response = { 'user': api_utils.package_user(user, True, send_token=True), 'new_friends': [enc.encrypt_key(f) for f in new_friends], 'new_user_details': new_user_details } try: levr.text_notify(user.display_name + ' from Foursquare!') except: levr.log_error() api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error() api_utils.send_error(self, '{}'.format(e))
def post(self,*args,**kwargs): #RESTRICTED try: logging.debug(kwargs) email = kwargs.get('email',None) alias = kwargs.get('alias',None) pw = kwargs.get('pw',None) '''Check availability of username+pass, create and login if not taken''' #check availabilities r_email = levr.Customer.gql('WHERE email = :1',email).get() r_alias = levr.Customer.gql('WHERE alias = :1',alias).get() #if taken, send error if r_email: api_utils.send_error(self,'That email is already registered.') return if r_alias: api_utils.send_error(self,'That alias is already registered.') return #still here? create a customer, then. user = levr.create_new_user( email=email, alias=alias, pw=enc.encrypt_password(pw)) #put and reply #create or refresh the alias user = levr.build_display_name(user) try: levr.text_notify(user.display_name+' from Levr!') except: levr.log_error() #put and reply user.put() response = {'user':api_utils.package_user(user,True,send_token=True)} api_utils.send_response(self,response,user) except: levr.log_error() api_utils.send_error(self,'Server Error')
class SignupFacebookHandler(webapp2.RequestHandler): @api_utils.validate(None, None, remoteToken=True) def post(self, *args, **kwargs): #RESTRICTED try: #check token facebook_token = kwargs.get('remoteToken', None) # user = levr.Customer.all().filter('facebook_id',facebook_id).get() user = social.Facebook(None, 'verbose', facebook_token=facebook_token) try: new_user, new_user_details, new_friends = user.first_time_connect( facebook_token=facebook_token, ) except Exception, e: levr.log_error() assert False, 'Could not connect with facebook.' #return the user response = { 'user': api_utils.package_user(new_user, True, send_token=True), 'new_friends': [enc.encrypt_key(f) for f in new_friends], 'new_user_details': new_user_details } try: levr.text_notify(new_user.display_name + 'from Facebook') except: levr.log_error() api_utils.send_response(self, response, new_user) except AssertionError, e: levr.log_error() api_utils.send_error(self, '{}'.format(e))
def post(self, *args, **kwargs): #RESTRICTED try: logging.debug(kwargs) email = kwargs.get('email', None) alias = kwargs.get('alias', None) pw = kwargs.get('pw', None) '''Check availability of username+pass, create and login if not taken''' #check availabilities r_email = levr.Customer.gql('WHERE email = :1', email).get() r_alias = levr.Customer.gql('WHERE alias = :1', alias).get() #if taken, send error if r_email: api_utils.send_error(self, 'That email is already registered.') return if r_alias: api_utils.send_error(self, 'That alias is already registered.') return #still here? create a customer, then. user = levr.create_new_user(email=email, alias=alias, pw=enc.encrypt_password(pw)) #put and reply #create or refresh the alias user = levr.build_display_name(user) try: levr.text_notify(user.display_name + ' from Levr!') except: levr.log_error() #put and reply user.put() response = { 'user': api_utils.package_user(user, True, send_token=True) } api_utils.send_response(self, response, user) except: levr.log_error() api_utils.send_error(self, 'Server Error')
class EditDealHandler(blobstore_handlers.BlobstoreUploadHandler): ''' A handler to upload new data for an existing deal in the database Will optionally receive an image. ''' def get(self): ''' A test form to test editing a deal ''' upload_url = blobstore.create_upload_url(EDIT_DEAL_UPLOAD_URL) logging.info(upload_url) # The method must be "POST" and enctype must be set to "multipart/form-data". 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( '''Upload File: <input type="file" name="img"><br>''') self.response.out.write( 'uid: <input type="text" name="uid" value="{}"> <br>'.format( 'tAvwdQhJqgEn8hL7fD1phb9z_c-GNGaQXr0fO3GJdErv19TaoeLGNiu51Stsm8gaChA=' )) self.response.out.write( 'levrToken: <input type="text" name="levrToken" value="{}"> <br>'. format('tFCBPw9A6gt2-Wq6K0RHxYQDkpPUFWvWD-FhCFSQCjM')) self.response.out.write( 'dealID: <input type="text" name="dealID" value="{}"> <br>'. format( 'tAvwdQhJqgEn8hL7fD1phb9z_c-GNGaQXr0fC3GJdErv19TaoeLGNiu51Stsm8gaChDyDrrMSui1aMhOG-0X' )) self.response.out.write( 'description: <input type="text" name="description" value="{}"> <br>' .format('description!!!')) self.response.out.write( 'dealText: <input type="text" name="dealText" value="{}"> <br>'. format('dealText!!!')) self.response.out.write( '<input type="submit"name="submit" value="Create!"> </form></body></html>' ) @api_utils.validate( None, 'param', user=True, deal=True, levrToken=True, description=False, dealText=False, ) @api_utils.private def post(self, *args, **kwargs): #@UnusedVariable ''' @keyword actor: required @keyword deal: required @keyword description: optional @keyword dealText: optional @var new_img_key: optional - the blob key of the uploaded image @return: the new deal object @rtype: dict ''' user = kwargs.get('actor') deal = kwargs.get('deal') description = kwargs.get('description', None) deal_text = kwargs.get('dealText', None) try: # assure that the user is the owner of the deal assert deal.parent_key() == user.key( ), 'User does not own that deal' #=================================================================== # Check for image upload #=================================================================== if self.get_uploads(): new_img_key = self.get_uploads()[0].key() # grab old key so we can delete it old_img_key = deal.img # replace with new key deal.img = new_img_key # delete that old key old_img_key.delete() try: # Synchronously rotate the image api_utils.rotate_image(new_img_key) except: levr.log_error('An image could not be rotated. \ It was sent to the task que: ' + str(new_img_key)) # Send the image to the img rotation task que task_params = {'blob_key': str(new_img_key)} logging.info('Sending this to the img rotation task: ' + str(task_params)) taskqueue.add(url=IMAGE_ROTATION_TASK_URL, payload=json.dumps(task_params)) else: assert description or deal_text, 'Thanks for sending me something to update.' #=================================================================== # Update new deal informations #=================================================================== if description: deal.description = description if deal_text: deal.deal_text = deal_text # TODO: add new tags to the deal for the new information that was added deal.put() private = True deals = api_utils.fetch_all_users_deals(user) packaged_deals = api_utils.package_deal_multi(deals, private) response = {'deals': packaged_deals} api_utils.send_response(self, response, user) except AssertionError, e: api_utils.send_error(self, e.message) except Exception, e: levr.log_error(e) api_utils.send_error(self, 'Server Error')
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,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): ''' Input: uid ''' try: logging.debug("REPORT\n\n\n") logging.debug(kwargs) user = kwargs.get('actor') deal = kwargs.get('deal') uid = user.key() dealID = deal.key() #create report Entity levr.ReportedDeal( uid = uid, dealID = dealID ).put() #is it a foursquare deal that got reported? if deal.origin == 'foursquare': #get the business business = levr.Business.get(deal.businessID) #get the business' foursquare ID foursquare_id = business.foursquare_id #is the user a foursquare user? if user.foursquare_token > '': token = user.foursquare_token else: token = 'random' #fire off a task to review the foursquare deals for this business task_params = { 'foursquare_id' : foursquare_id, 'token' : token, 'deal_id' : str(deal.key()), 'uid' : str(user.key()), 'deal_status' : deal.deal_status } taskqueue.add(url='/tasks/foursquareDealUpdateTask',payload=json.dumps(task_params)) #send notification via email message = mail.EmailMessage( sender ="LEVR AUTOMATED <*****@*****.**>", subject ="New Reported Deal", to ="*****@*****.**") logging.debug(message) body = 'New Reported Deal\n\n' body += levr.log_model_props(user, ['email','display_name','']) body += str(user.email) +' is reporting '+str(deal.deal_text) message.body = body logging.debug(message.body) message.send() api_utils.send_response(self,{},user) except: levr.log_error() api_utils.send_error(self,'Server Error')
def post(self, *args, **kwargs): #@UnusedVariable ''' @keyword actor: required @keyword deal: required @keyword description: optional @keyword dealText: optional @var new_img_key: optional - the blob key of the uploaded image @return: the new deal object @rtype: dict ''' user = kwargs.get('actor') deal = kwargs.get('deal') description = kwargs.get('description', None) deal_text = kwargs.get('dealText', None) try: # assure that the user is the owner of the deal assert deal.parent_key() == user.key( ), 'User does not own that deal' #=================================================================== # Check for image upload #=================================================================== if self.get_uploads(): new_img_key = self.get_uploads()[0].key() # grab old key so we can delete it old_img_key = deal.img # replace with new key deal.img = new_img_key # delete that old key old_img_key.delete() try: # Synchronously rotate the image api_utils.rotate_image(new_img_key) except: levr.log_error('An image could not be rotated. \ It was sent to the task que: ' + str(new_img_key)) # Send the image to the img rotation task que task_params = {'blob_key': str(new_img_key)} logging.info('Sending this to the img rotation task: ' + str(task_params)) taskqueue.add(url=IMAGE_ROTATION_TASK_URL, payload=json.dumps(task_params)) else: assert description or deal_text, 'Thanks for sending me something to update.' #=================================================================== # Update new deal informations #=================================================================== if description: deal.description = description if deal_text: deal.deal_text = deal_text # TODO: add new tags to the deal for the new information that was added deal.put() private = True deals = api_utils.fetch_all_users_deals(user) packaged_deals = api_utils.package_deal_multi(deals, private) response = {'deals': packaged_deals} api_utils.send_response(self, response, user) except AssertionError, e: api_utils.send_error(self, e.message)
def post(self): #curl --data 'businessName=alonsostestbusiness&vicinity=testVicinity&phone=%2B16052610083&geoPoint=-71.234,43.2345' http://www.levr.com/api/merchant/initialize | python -mjson.tool '''REMEMBER PHONE NUMBER FORMATTING STUFF''' api_utils.send_error(self,'Hey ethan. Ask alonso about the formatting of the phone number.') return #Grab incoming merchant data business_name = self.request.get('businessName') if business_name == '': api_utils.send_error(self,'Required parameter not passed: businessName') return vicinity = self.request.get('vicinity') if vicinity == '': api_utils.send_error(self,'Required parameter not passed: vicinity') return phone = self.request.get('phone') if phone == '': api_utils.send_error(self,'Required parameter not passed: phone') return geo_point = self.request.get('geoPoint') if geo_point == '': api_utils.send_error(self,'Required parameter not passed: geo_point') return #check if business entity already exists based on phone number business = levr.Business.gql('WHERE business_name = :1 AND phone = :2',business_name,phone).get() if business: #if a business has been created and an owner has been set, return an error if business.owner: logging.info('Owner is set!') api_utils.send_error(self,'That business has already been verified. If you need help, email [email protected]') return #if a business has been created but no owner has been set, return the business else: logging.debug('Creating a new business.') #create a new business entity with no owner business = levr.Business() business.business_name = business_name business.vicinity = vicinity business.phone = phone business.geo_point = levr.geo_converter(geo_point) business.activation_code = str(int(time.time()))[-4:] #put business.put() #reply with business object response = {'business':api_utils.package_business(business)} api_utils.send_response(self,response)
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): #@UnusedVariable ''' @keyword actor: required @keyword business: required @keyword description: required @keyword deal_text: required @keyword development: required @requires: an image is uploaded - need the blob_key @return: the newly created deal object @rtype: dict ''' user = kwargs.get('actor') business = kwargs.get('business') description = kwargs.get('description') deal_text = kwargs.get('dealText') development = kwargs.get('development') img_key = '' try: #=================================================================== # Assure that an image was uploaded #=================================================================== if self.get_uploads(): 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') #=================================================================== # Assemble the deal parameters! And create the deal!! #=================================================================== params = { 'user' : user, 'uid' : user.key(), 'business' : business, 'deal_description' : description, 'deal_line1' : deal_text, 'development' : development, 'img_key' : img_key } # TODO: add pin_color = 'green' to the deal # TODO: add origin = 'merchant' deal_entity = levr.dealCreate(params, 'phone_merchant', upload_flag) # if an image was uploaded, rotate it. if upload_flag == True: try: # Synchronously rotate the image api_utils.rotate_image(blob_key,deal_entity) except: levr.log_error('An image could not be rotated. It was sent to the task que: '+str(blob_key)) # Send the image to the img rotation task que task_params = { 'blob_key' : str(blob_key) } logging.info('Sending this to the img rotation task: '+str(task_params)) taskqueue.add(url=IMAGE_ROTATION_TASK_URL,payload=json.dumps(task_params)) #=================================================================== # Aw hell.. why not give them some karma too. #=================================================================== user.karma += 5 # no need to level_check on them though... user.put() #=================================================================== # Create some nifty notifications #=================================================================== try: levr.create_notification('followedUpload',user.followers,user.key(),deal_entity) except: levr.log_error() #=================================================================== # Respond with all of the users deals #=================================================================== private = True deals = api_utils.fetch_all_users_deals(user) packaged_deals = api_utils.package_deal_multi(deals, private) response = { 'deals' : packaged_deals } api_utils.send_response(self,response, user) except Exception,e: levr.log_error(e) api_utils.send_error(self,'Server Error')
def post(self,*args,**kwargs): #@UnusedVariable ''' @keyword actor: required @keyword deal: required @keyword description: optional @keyword dealText: optional @var new_img_key: optional - the blob key of the uploaded image @return: the new deal object @rtype: dict ''' user = kwargs.get('actor') deal = kwargs.get('deal') description = kwargs.get('description',None) deal_text = kwargs.get('dealText',None) try: # assure that the user is the owner of the deal assert deal.parent_key() == user.key(), 'User does not own that deal' #=================================================================== # Check for image upload #=================================================================== if self.get_uploads(): new_img_key = self.get_uploads()[0].key() # grab old key so we can delete it old_img_key = deal.img # replace with new key deal.img = new_img_key # delete that old key old_img_key.delete() try: # Synchronously rotate the image api_utils.rotate_image(new_img_key) except: levr.log_error('An image could not be rotated. \ It was sent to the task que: '+str(new_img_key)) # Send the image to the img rotation task que task_params = { 'blob_key' : str(new_img_key) } logging.info('Sending this to the img rotation task: '+str(task_params)) taskqueue.add(url=IMAGE_ROTATION_TASK_URL,payload=json.dumps(task_params)) else: assert description or deal_text, 'Thanks for sending me something to update.' #=================================================================== # Update new deal informations #=================================================================== if description: deal.description = description if deal_text: deal.deal_text = deal_text # TODO: add new tags to the deal for the new information that was added deal.put() private = True deals = api_utils.fetch_all_users_deals(user) packaged_deals = api_utils.package_deal_multi(deals, private) response = { 'deals' : packaged_deals } api_utils.send_response(self,response, user) except AssertionError,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 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): 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)
logging.debug(levr.log_model_props(user)) logging.debug(str(new_user_details)) #return the user response = { 'user': api_utils.package_user(user, True), 'new_friends': [enc.encrypt_key(f) for f in new_friends], 'new_user_details': new_user_details } api_utils.send_response(self, response, user) except AssertionError, e: levr.log_error() api_utils.send_error(self, '{}'.format(e.message)) except: levr.log_error() api_utils.send_error(self, 'Server Error') class ConnectFoursquareHandler(webapp2.RequestHandler): @api_utils.validate(None, 'param', user=True, remoteToken=True, levrToken=True) #id=True @api_utils.private def post(self, *args, **kwargs): try: #RESTRICTED logging.debug('CONNECT FOURSQUARE\n\n\n') logging.debug(kwargs)
'new_friends' : [enc.encrypt_key(f) for f in new_friends], 'new_user_details' : new_user_details } try: levr.text_notify(new_user.display_name + 'from Facebook') except: levr.log_error() api_utils.send_response(self,response,new_user) except AssertionError,e: levr.log_error() api_utils.send_error(self,'{}'.format(e)) except Exception,e: levr.log_error() api_utils.send_error(self,'Server Error') class SignupFoursquareHandler(webapp2.RequestHandler): @api_utils.validate(None,None,remoteToken=True) def post(self,*args,**kwargs): try: #check token foursquare_token = kwargs.get('remoteToken',None) user = levr.Customer.all().filter('foursquare_token',foursquare_token).get() if user: #fallback to login response = { 'user':api_utils.package_user(user,True,send_token=True)
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')
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)) except: logging.info("Server Error") logging.info(str(e)) levr.log_error() api_utils.send_error(self, "Server Error") app = webapp2.WSGIApplication( [("/api/upload/request", UploadRequestHandler), ("/api/upload/post", UploadPostHandler)], debug=True )