def update_friends(self,friends=None): ''' Foursquare 1. Makes a call to foursquare to pull all of the users friends 2. Pulls the facebook, twitter, email, and foursquare info from each friend with that info 3. Adds that information to a corresponding list on the user entity 4. Creates the db linkage between user and friends by calling create_notification ''' logging.debug('\n\n FOURSQUARE UPDATE FRIENDS \n\n') #get the users friends if not friends: logging.debug('FRIEND DATA DOES NOT EXIST... make fetch') content = self.fetch('friends') logging.debug(levr.log_dict(content)) friends = content['response']['friends']['items'] else: logging.debug('FRIEND DATA EXISTS... do not make fetch') logging.debug(levr.log_dict(friends)) #grab all friend informations foursquare_friends = [] twitter_friends_by_sn = [] facebook_friends = [] email_friends = [] for f in friends: logging.debug(f) foursquare_friends.append(int(f['id'])) contact = f['contact'] if 'twitter' in contact: twitter_friends_by_sn.append(contact['twitter']) if 'facebook' in contact: facebook_friends.append(int(contact['facebook'])) if 'email' in contact: email_friends.append(contact['email']) logging.debug(twitter_friends_by_sn) logging.debug('\n\n') logging.debug(facebook_friends) logging.debug('\n\n') logging.debug(foursquare_friends) logging.debug('\n\n') #store the information for the users facebook friends that were just found self.extend_friends( twitter_friends_by_sn=twitter_friends_by_sn, facebook_friends=facebook_friends, foursquare_friends=foursquare_friends ) #Create the connection between the user and their friends new_friends = self.connect_friends() return new_friends
def update_friends(self, friends=None): ''' Foursquare 1. Makes a call to foursquare to pull all of the users friends 2. Pulls the facebook, twitter, email, and foursquare info from each friend with that info 3. Adds that information to a corresponding list on the user entity 4. Creates the db linkage between user and friends by calling create_notification ''' logging.debug('\n\n FOURSQUARE UPDATE FRIENDS \n\n') #get the users friends if not friends: logging.debug('FRIEND DATA DOES NOT EXIST... make fetch') content = self.fetch('friends') logging.debug(levr.log_dict(content)) friends = content['response']['friends']['items'] else: logging.debug('FRIEND DATA EXISTS... do not make fetch') logging.debug(levr.log_dict(friends)) #grab all friend informations foursquare_friends = [] twitter_friends_by_sn = [] facebook_friends = [] email_friends = [] for f in friends: logging.debug(f) foursquare_friends.append(int(f['id'])) contact = f['contact'] if 'twitter' in contact: twitter_friends_by_sn.append(contact['twitter']) if 'facebook' in contact: facebook_friends.append(int(contact['facebook'])) if 'email' in contact: email_friends.append(contact['email']) logging.debug(twitter_friends_by_sn) logging.debug('\n\n') logging.debug(facebook_friends) logging.debug('\n\n') logging.debug(foursquare_friends) logging.debug('\n\n') #store the information for the users facebook friends that were just found self.extend_friends(twitter_friends_by_sn=twitter_friends_by_sn, facebook_friends=facebook_friends, foursquare_friends=foursquare_friends) #Create the connection between the user and their friends new_friends = self.connect_friends() return new_friends
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 post(self): try: logging.info(''' SKYNET IS TEXTING THE FOUNDERS ''') payload = json.loads(self.request.body) logging.info(payload['user_string']) #twilio credentials sid = 'AC4880dbd1ff355288728be2c5f5f7406b' token = 'ea7cce49e3bb805b04d00f76253f9f2b' twiliourl='https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/SMS/Messages.json' auth_header = 'Basic '+base64.b64encode(sid+':'+token) logging.info(auth_header) numbers = ['+16052610083','+16035605655','+16173124536','+16173124536','+12036329029'] for number in numbers: request = {'From':'+16173608582', 'To':number, 'Body':'Awwwww yeeeaahhhhh. You have a new user: '******'user_string']} result = urlfetch.fetch(url=twiliourl, payload=urllib.urlencode(request), method=urlfetch.POST, headers={'Authorization':auth_header}) logging.info(levr.log_dict(result.__dict__)) except: levr.log_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 update_user_details(self): ''' Twitter ''' content = self.fetch('user') logging.debug('\n\n\t\t\t\t UPDATE USER DETAILS \n\n') logging.debug(levr.log_dict(content)) updated = {} #update twitter info twitter_id = content.get('id') screen_name = content.get('screen_name') if not self.user.twitter_id: self.user.twitter_id = twitter_id updated['twitter_id'] = twitter_id if not self.user.twitter_screen_name: self.user.twitter_screen_name = screen_name updated['twitter_screen_name'] = screen_name #update general attributes if not self.user.facebook_connected: photo = content.get('profile_image_url_https') name = content.get('name') names = name.split(' ') first_name = names[0] last_name = names[-1] display_name= self.build_display_name(first_name, last_name) #update user values if they are to be update # if not self.user.photo: #keep photo up to date self.user.photo = photo updated['photo'] = photo if not self.user.first_name or not self.user.last_name: self.user.display_name = display_name updated['display_name'] = display_name if not self.user.first_name: self.user.first_name = first_name updated['first_name'] = first_name if not self.user.last_name: self.user.last_name = last_name updated['last_name'] = last_name if not self.user.display_name: self.user.display_name = display_name updated['display_name'] else: return updated raise Exception('User has already connected with facebook') #parse details return updated
def update_user_details(self): ''' Twitter ''' content = self.fetch('user') logging.debug('\n\n\t\t\t\t UPDATE USER DETAILS \n\n') logging.debug(levr.log_dict(content)) updated = {} #update twitter info twitter_id = content.get('id') screen_name = content.get('screen_name') if not self.user.twitter_id: self.user.twitter_id = twitter_id updated['twitter_id'] = twitter_id if not self.user.twitter_screen_name: self.user.twitter_screen_name = screen_name updated['twitter_screen_name'] = screen_name #update general attributes if not self.user.facebook_connected: photo = content.get('profile_image_url_https') name = content.get('name') names = name.split(' ') first_name = names[0] last_name = names[-1] display_name = self.build_display_name(first_name, last_name) #update user values if they are to be update # if not self.user.photo: #keep photo up to date self.user.photo = photo updated['photo'] = photo if not self.user.first_name or not self.user.last_name: self.user.display_name = display_name updated['display_name'] = display_name if not self.user.first_name: self.user.first_name = first_name updated['first_name'] = first_name if not self.user.last_name: self.user.last_name = last_name updated['last_name'] = last_name if not self.user.display_name: self.user.display_name = display_name updated['display_name'] else: return updated raise Exception('User has already connected with facebook') #parse details return updated
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 fetch(self, action): ''' SocialClass Makes a request to an api using the url and action specified Returns the result json ''' logging.debug('\n\n DEFAULT FETCH DATA \n\n') url, method, headers = self.create_url(action) logging.debug('\n\n DEFAULT FETCH DATA \n\n') logging.debug(url) response = urlfetch.fetch( url=url, method=method, headers=headers) # logging.debug(levr.log_dir(response)) # logging.debug(result.status_code) # logging.debug(result.headers.data) # logging.debug(response.content) logging.debug(response.status_code) logging.debug(response.headers.data) logging.debug(response.content) if response.status_code == 200: #request success content = json.loads(response.content) else: #request failed try: content = levr.log_dict(json.loads(response.content)) headers = levr.log_dict(response.headers.data) except: content = 'Content could not be fetched\n\n' headers = levr.log_dict(response.headers.data) raise Exception('Could Not connect:' +headers+ content) # content = self.handle_fetch_response(content) return content
def fetch(self, action): ''' SocialClass Makes a request to an api using the url and action specified Returns the result json ''' logging.debug('\n\n DEFAULT FETCH DATA \n\n') url, method, headers = self.create_url(action) logging.debug('\n\n DEFAULT FETCH DATA \n\n') logging.debug(url) response = urlfetch.fetch(url=url, method=method, headers=headers) # logging.debug(levr.log_dir(response)) # logging.debug(result.status_code) # logging.debug(result.headers.data) # logging.debug(response.content) logging.debug(response.status_code) logging.debug(response.headers.data) logging.debug(response.content) if response.status_code == 200: #request success content = json.loads(response.content) else: #request failed try: content = levr.log_dict(json.loads(response.content)) headers = levr.log_dict(response.headers.data) except: content = 'Content could not be fetched\n\n' headers = levr.log_dict(response.headers.data) raise Exception('Could Not connect:' + headers + content) # content = self.handle_fetch_response(content) return content
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 post(self): try: logging.info(''' SKYNET IS TEXTING THE FOUNDERS ''') payload = json.loads(self.request.body) logging.info(payload['user_string']) #twilio credentials sid = 'AC4880dbd1ff355288728be2c5f5f7406b' token = 'ea7cce49e3bb805b04d00f76253f9f2b' twiliourl = 'https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/SMS/Messages.json' auth_header = 'Basic ' + base64.b64encode(sid + ':' + token) logging.info(auth_header) numbers = [ '+16052610083', '+16035605655', '+16173124536', '+16173124536', '+12036329029' ] for number in numbers: request = { 'From': '+16173608582', 'To': number, 'Body': 'Awwwww yeeeaahhhhh. You have a new user: '******'user_string'] } result = urlfetch.fetch(url=twiliourl, payload=urllib.urlencode(request), method=urlfetch.POST, headers={'Authorization': auth_header}) logging.info(levr.log_dict(result.__dict__)) except: levr.log_error()
def __init__(self, user=None, *args, **kwargs): ''' Foursquare ''' logging.debug('\n\n\n \t\t\t INIT FOURSQUARE \n\n\n') #set the foursquare api version self.version = '20121007' #the foursquare api version if 'debug' in args: foursquare_token = kwargs.get('foursquare_token') self.foursquare_token = foursquare_token if not user: #user was not passed, check to make sure that the user does not already exist # if the user exists, pass it to SocialClass.__init__ # otherwise, create a new user and pass it that foursquare_token = kwargs.get('foursquare_token') #make sure foursquare token was passed assert foursquare_token, 'Did not pass a user, so must pass foursquare_token as kwarg' #assign the foursquare_token so that self.fetch will work self.foursquare_token = foursquare_token #fetch the user info response = self.fetch('') logging.debug(levr.log_dict(response)) #get the user id foursquare_id = int(response['response']['user']['id']) #search for the user by that id user = levr.Customer.all().filter('foursquare_id', foursquare_id).get() # logging.debug('\n\n\n\n \t\t\t\t USER \n\n\n\n') logging.debug(user) logging.debug(levr.log_model_props(user)) if not user: logging.debug('user doesnt exist') #user does not exist in database - create a new one! user = levr.create_new_user() else: logging.debug('user exists') # else: user was found and we will init with that user #init all dat social stuff! SocialClass.__init__(self, user, *args, **kwargs)
def __init__(self, user=None, *args, **kwargs): ''' Foursquare ''' logging.debug('\n\n\n \t\t\t INIT FOURSQUARE \n\n\n') #set the foursquare api version self.version = '20121007' #the foursquare api version if 'debug' in args: foursquare_token = kwargs.get('foursquare_token') self.foursquare_token = foursquare_token if not user: #user was not passed, check to make sure that the user does not already exist # if the user exists, pass it to SocialClass.__init__ # otherwise, create a new user and pass it that foursquare_token = kwargs.get('foursquare_token') #make sure foursquare token was passed assert foursquare_token, 'Did not pass a user, so must pass foursquare_token as kwarg' #assign the foursquare_token so that self.fetch will work self.foursquare_token = foursquare_token #fetch the user info response = self.fetch('') logging.debug(levr.log_dict(response)) #get the user id foursquare_id = int(response['response']['user']['id']) #search for the user by that id user = levr.Customer.all().filter('foursquare_id',foursquare_id).get() # logging.debug('\n\n\n\n \t\t\t\t USER \n\n\n\n') logging.debug(user) logging.debug(levr.log_model_props(user)) if not user: logging.debug('user doesnt exist') #user does not exist in database - create a new one! user = levr.create_new_user() else: logging.debug('user exists') # else: user was found and we will init with that user #init all dat social stuff! SocialClass.__init__(self, user, *args, **kwargs)
def call_merchant(business): #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/merchants/verify/answer', 'StatusCallback':'http://www.levr.com/merchants/verify/statusCallback'} 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): 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 __init__(self, user=None, *args, **kwargs): ''' Facebook ''' logging.debug('\n\n\n \t\t\t INIT FACEBOOK \n\n\n') self.set_noise_level(*args) # if user is not passed, then check if a user exists with the identity specified. if they do not exist, then create a new one if not user: #user was not passed, check to make sure that the user does not already exist # if the user exists, pass it to SocialClass.__init__ # otherwise, create a new user and pass it that facebook_token = kwargs.get('facebook_token') #make sure foursquare token was passed assert facebook_token, 'Did not pass a user, so must pass facebook_token as kwarg' #assign the foursquare_token so that self.fetch will work self.facebook_token = facebook_token #fetch the user info from facebook response = self.fetch('user') logging.debug(levr.log_dict(response)) #get the user id from the remote api call facebook_id = int(response['id']) #search for the user in our db by that id user = levr.Customer.all().filter('facebook_id',facebook_id).get() # logging.debug('\n\n\n\n \t\t\t\t USER \n\n\n\n') logging.debug(user) logging.debug(levr.log_model_props(user)) if not user: logging.debug('user doesnt exist') #user does not exist in database - create a new one! user = levr.create_new_user() else: logging.debug('user exists') # else: user was found and we will init with that user logging.debug(user) #init all dat social stuff! SocialClass.__init__(self, user, *args, **kwargs)
def __init__(self, user=None, *args, **kwargs): ''' Facebook ''' logging.debug('\n\n\n \t\t\t INIT FACEBOOK \n\n\n') self.set_noise_level(*args) # if user is not passed, then check if a user exists with the identity specified. if they do not exist, then create a new one if not user: #user was not passed, check to make sure that the user does not already exist # if the user exists, pass it to SocialClass.__init__ # otherwise, create a new user and pass it that facebook_token = kwargs.get('facebook_token') #make sure foursquare token was passed assert facebook_token, 'Did not pass a user, so must pass facebook_token as kwarg' #assign the foursquare_token so that self.fetch will work self.facebook_token = facebook_token #fetch the user info from facebook response = self.fetch('user') logging.debug(levr.log_dict(response)) #get the user id from the remote api call facebook_id = int(response['id']) #search for the user in our db by that id user = levr.Customer.all().filter('facebook_id', facebook_id).get() # logging.debug('\n\n\n\n \t\t\t\t USER \n\n\n\n') logging.debug(user) logging.debug(levr.log_model_props(user)) if not user: logging.debug('user doesnt exist') #user does not exist in database - create a new one! user = levr.create_new_user() else: logging.debug('user exists') # else: user was found and we will init with that user logging.debug(user) #init all dat social stuff! SocialClass.__init__(self, user, *args, **kwargs)
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 call_merchant(business): #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/merchants/verify/answer', 'StatusCallback': 'http://www.levr.com/merchants/verify/statusCallback' } 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): #@UnusedVariable ''' inputs: lat,lon,limit, query response:{ [string,string] } /api/search/all? lat=42.357632 &lon=-71.089432 &limit=50 &offset=0 &uid=tAvwdQhJqgEn8hL7fD1phb9z_c-GNGaQXr0fO3GJdErv19TaoeLGNiu51St9sfoYChA= &levrToken=7ALUawsTs1R3_z_pK0YTx4cCkpfSFzuDCOM1XQCXWDM &latitudeHalfDelta=0.023277 &longitudeHalfDelta=0.027466 ''' try: tstart = datetime.now() logging.debug('SEARCH BY QUERY \n\n\n') # logging.debug(kwargs) #GET PARAMS logging.info(kwargs) #assert False geo_point = kwargs.get('geoPoint') # radius = kwargs.get('radius') # limit = kwargs.get('limit') query = kwargs.get('query','all') development = kwargs.get('development',False) user = kwargs.get('actor') lon_half_delta = kwargs.get('longitudeHalfDelta',0) # lat_half_delta = kwargs.get('latitudeHalfDelta') try: logging.info(user.display_name) except: logging.info('unkown user') times = {} search = api_utils.Search(development,user) # calc precision precision = search.calc_precision_from_half_deltas(geo_point, lon_half_delta) # create ghashes ghash_list = search.create_ghash_list(geo_point, precision) # calc bounding box bounding_box = search.calc_bounding_box(ghash_list) # fetch all deals in the ghash range t1 = datetime.now() deals = search.fetch_deals(ghash_list) times.update({'fetch_deals_time':str(datetime.now() - t1)}) # filter deals by search query t1 = datetime.now() num_results,accepted_deals= search.filter_deals_by_query(deals, query) times.update({'filter_deals_time': str(datetime.now() - t1)}) # increment deal views on levr deals search.add_deal_views(deals) # init package time if query != 'all' and accepted_deals.__len__() != 0: t1 = datetime.now() packaged_deals = search.sort_and_package(accepted_deals) package_time = datetime.now()-t1 else: # act like a search all, use all deals # decompose deals by origin levr_deals, foursquare_deals = search.filter_deals_by_origin(deals) if levr_deals.__len__() >5: t1 = datetime.now() packaged_deals = search.sort_and_package(levr_deals) package_time = datetime.now()-t1 # qualify search results. do we need more? else: t1 = datetime.now() packaged_deals = search.sort_and_package(deals) package_time = datetime.now()-t1 # add foursquare deals if foursquare_deals.__len__() < 5: # search for more foursquare deals try: # grab search information token = search.foursquare_token deal_status = search.deal_status foursquare_ids = search.get_foursquare_ids(deals) # make remote call to foursquare ft1 = datetime.now() new_foursquare_deals = api_utils.search_foursquare(geo_point,token,deal_status,foursquare_ids) times.update({'foursquare_search_time':str(datetime.now()-ft1)}) # add new foursquare deals packaged_deals.extend(new_foursquare_deals) except: levr.log_error('Error in foursquare call or parsing.') times.update({'package_time':package_time}) # else: # params = { # 'lat' : geo_point.lat, # 'lon' : geo_point.lon, # 'token' : token, # 'foursquare_ids': foursquare_ids, # 'deal_status' : deal_status # } # # logging.debug('Sending this to the task: ' + json.dumps(params)) # # #start the task # taskqueue.add(url='/tasks/searchFoursquareTask',payload=json.dumps(params)) times.update({'total_time':datetime.now()-tstart}) #=================================================================== # Send response #=================================================================== logging.info(levr.log_dict(times)) times = {key:str(times[key]) for key in times} response = { 'searchPoint' : str(geo_point), 'numResults' : num_results, 'boundingBox' : bounding_box, # 'ending_hashes' : list(searched_hash_set), 'num_total_results' : packaged_deals.__len__(), 'deals' : packaged_deals, 'times' : times } try: response.update({ 'user' : api_utils.package_user(self.user, True, False) }) except: logging.info('user not passed') # assert False, response self.send_response(response) except: levr.log_error() self.send_error()
def get(self): try: logging.debug('Hit the Authorize Complete Handler') client_id = facebook_auth['client_id'] client_secret = facebook_auth['client_secret'] #======================================================================= # Fetch access_token from facebook #======================================================================= #check for error error = self.request.get('error',None) assert error == None, 'User denied request' state = self.request.get('state',None) code = self.request.get('code',None) logging.debug(state) logging.debug(code) redirect_uri = 'http://levr-production.appspot.com/facebook/authorize/complete' url = 'https://graph.facebook.com/oauth/access_token?client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}'.format( client_id= client_id, redirect_uri= redirect_uri, client_secret= client_secret, code= code) # Fetch the access token from facebook result = urlfetch.fetch(url=url) logging.debug(result.content) logging.debug(type(result.content)) logging.debug(levr.log_dir(result.content)) facebook_token = result.content.split('&')[0].split('=')[1] logging.debug(facebook_token) #======================================================================= # Create User and connect them with levr #======================================================================= #wrap the user in the social class - creates new user if user doesnt exist user = social.Facebook(facebook_token=facebook_token) user,new_details,new_friends = user.first_time_connect(facebook_token=facebook_token) logging.debug(levr.log_model_props(user)) logging.debug(levr.log_dict(new_details)) logging.debug(levr.log_dict(new_friends)) try: logging.debug(user.display_name) logging.debug(user.first_name) logging.debug(user.last_name) logging.debug(user.facebook_id) except: levr.log_error() #send the founders a text levr.text_notify(user.first_name + ' ' + user.last_name + ' from facebook') #set up the jinja template and echo out # template = jinja_environment.get_template('templates/deal.html') # self.response.out.write(template.render(template_values)) self.response.out.write('Hooray! you are connected with levr!') logging.debug(levr.log_dict(user)) except: levr.log_error() self.response.out.write('Could not connect with Facebook')
def update_user_details(self,content=None): ''' Foursqaure Grabs the users personal information from foursquare and updates the user if content is passed, it should be the user dict responded by foursquare ''' logging.debug('\n\n FOURSQUARE UPDATE USER DETAILS PREFETCH \n\n') #get foursquare details if not content: logging.debug('USER CONTENT WAS NOT PASSED... fetch data') foursquare_response = self.fetch('') content = foursquare_response['response']['user'] else: logging.debug('USER CONTENT WAS PASSED... do not fetch data') pass logging.debug('\n\n FOURSQUARE UPDATE USER DETAILS POSTFETCH \n\n') # logging.debug(foursquare_response) logging.debug(levr.log_dict(content)) logging.debug(type(content)) #give preference to facebook and twitter info over foursquare info #grab stuff updated = {} #update the users foursquare_id foursquare_id = int(content.get('id',None)) assert foursquare_id, "foursquare_id was not retrieved" if not self.user.foursquare_id: self.user.foursquare_id = foursquare_id updated['foursquare_id']= foursquare_id #update the rest of the users properties if not self.user.facebook_connected and not self.user.twitter_connected: # vals = { # 'first_name' : content['firstName'], # 'last_name' : content['lastName'], # 'display_name' : self.build_display_name(first_name, last_name), # 'photo' : content['photo']['prefix'] + '500x500' + content['photo']['suffix'], # 'email' : content['contact']['email'], # 'foursquare_id' : int(content['id']) # # } first_name = content.get('firstName','') #content['firstName'] last_name = content.get('lastName','') #content['lastName'] display_name = self.build_display_name(first_name, last_name) photo = content.get('photo',None) if photo: photo = photo.get('prefix','')+'500x500'+photo.get('suffix','') # photo = content['photo']['prefix'] + '500x500' + content['photo']['suffix'] contact = content.get('contact',None) if contact: email = contact.get('email') # email = content['contact']['email'] if not self.user.first_name: self.user.first_name = first_name updated['first_name'] = first_name if not self.user.last_name: self.user.last_name = last_name updated['last_name'] = last_name if not self.user.display_name: self.user.display_name = display_name updated['display_name'] = display_name # if not self.user.photo: #keep photo up to date self.user.photo = photo updated['photo'] = photo #grab email if not self.user.email: self.user.email = email updated['email'] = email logging.debug(levr.log_model_props(self.user)) else: # raise Exception('user has already connected with facebook or twitter') logging.info('user has already connected with facebook or twitter') return updated
def post(self): try: logging.debug('Foursquare push request received!') logging.debug(self.request.body) checkin = json.loads(self.request.get('checkin')) secret = self.request.get('secret') logging.debug(checkin) #verify that the secret passed matches ours hc_secret = 'VLKDNIT0XSA5FK3XIO05DAWVDVOXTSUHPE4H4WOHNIZV14G3' if hc_secret != secret: #raise an exception logging.debug('SECRETS DO NOT MATCH') #go look in our database for a matching foursquare venue id business = levr.Business.gql('WHERE foursquare_id = :1', checkin["venue"]["id"]).get() #business = levr.Business.get('ahFzfmxldnItcHJvZHVjdGlvbnIQCxIIQnVzaW5lc3MY-dIBDA') user = levr.Customer.gql('WHERE foursquare_id = :1', int(checkin['user']['id'])).get() #initialize the response object - these are defaults contentID = levr.create_content_id('foursquare') levr_url = 'http://www.levr.com/mobile/' + contentID #search for expired offers at that business #q_expired = levr.Deal.gql('WHERE businessID=:1 AND deal_status=:2',business) if business: #business found - CURRENTLY ONLY REPLYING AT BUSINESSES THAT ARE IN OUR DATABASE #for deal in levr.Deal.all().filter('businessID =', str(business.key())).run(): q = levr.Deal.gql( "WHERE businessID = :1 AND deal_status = :2 ORDER BY count_redeemed DESC", str(business.key()), 'active') deal = None for d in q: if d.origin != 'foursquare': deal = d text = 'Click to view the most popular offer here: ' + deal.deal_text action = 'deal' break else: text = "See any deals? Pay it forward! Click to add." action = 'upload' deal = None # # # numdeals = q.count() # if numdeals > 0: #many deals found # deal_matched = False # text = "See any deals? Pay it forward! Click to add." # action = 'upload' # while deal_matched == False: # deal = q.get() # if deal.origin != 'foursquare': # text = 'Click to view the most popular offer here: '+ deal.deal_text # action='deal' # deal_matched = True # else: #no deals found # text = "See any deals? Pay it forward! Click to add." # action = 'upload' #create floating_content entity and put floating_content = levr.FloatingContent(action=action, origin='foursquare', contentID=contentID, user=user, deal=deal, business=business) floating_content.put() try: #track event via mixpanel (asynchronous) properties = { 'time': time.time(), 'distinct_id': enc.encrypt_key(user.key()), 'mp_name_tag': user.display_name, 'action': action } mp_track.track('Foursquare checkin reply', "ab1137787f393161bd481e2756b77850", properties) user_props = { '$first_name': user.first_name, '$last_name': user.last_name, '$email': user.email } mp_track.person(enc.encrypt_key(user.key()), "ab1137787f393161bd481e2756b77850", user_props) to_increment = {"Checkins Served": 1} if action == 'deal': to_increment.update({'Deals Served': 1}) elif action == 'upload': to_increment.update({'Uploads Prompted': 1}) mp_track.increment(enc.encrypt_key(user.key()), "ab1137787f393161bd481e2756b77850", to_increment) except: levr.log_error() reply = { 'CHECKIN_ID': checkin['id'], 'text': text, 'url': levr_url, 'contentId': contentID } '''else: #no business found #ask pat for all the deals within walking distance url = 'http://www.levr.com/phone' ll = str(checkin['venue']['location']['lat'])+','+str(checkin['venue']['location']['lng']) request_point = levr.geo_converter(ll) precision = 6 results = levr_utils.get_deals_in_area(['all'],request_point,precision) if len(results) > 0: reply['text'] = "There are "+str(len(results))+" deals near you - click to view." reply['url'] = '' #deeplink into deal upload screen else: reply['text'] = "See any deals? Pay it forward: click to upload." reply['url'] = '' #deeplink into deal upload screen''' #reply['CHECKIN_ID'] = checkin['id'] #reply['text'] = 'Hey ethan. click here to see this reply inside Levr.' #reply['url'] = 'fsq+unhlif5eyxsklx50dasz2pqbge2hdoik5gxbwcirc55nmq4c+reply://?contentId=abcdefg12345&fsqCallback=foursquare://checkins/'+checkin['id'] #reply['url'] = 'fsq+unhlif5eyxsklx50dasz2pqbge2hdoik5gxbwcirc55nmq4c+reply://?contentId=abcdefg12345' #reply['url'] = 'http://www.levr.com?contentId=abcdefg12345' #reply['url'] = 'http://www.levr.com/deal/blah' #reply['contentId'] = 'abcdefg12345' url = 'https://api.foursquare.com/v2/checkins/' + checkin[ 'id'] + '/reply?v=20120920&oauth_token=' + user.foursquare_token #url = 'https://api.foursquare.com/v2/checkins/'+reply['CHECKIN_ID']+'/reply?v=20120920&text=hitherehello&url=foursquare%2Bunhlif5eyxsklx50dasz2pqbge2hdoik5gxbwcirc55nmq4c%2Breply%3A//%3FcontentId%3Dabcdefg12345&contentId=abcdefg12345&oauth_token='+'PZVIKS4EH5IFBJX1GH5TUFYAA3Z5EX55QBJOE3YDXKNVYESZ' logging.debug(url) #result = urlfetch.fetch(url=url,method=urlfetch.POST) result = urlfetch.fetch(url=url, payload=urllib.urlencode(reply), method=urlfetch.POST) logging.debug(levr.log_dict(result.__dict__)) else: logging.info('BUSINESS NOT FOUND') except: levr.log_error() self.reponse.out.write('Could not connect with Foursquare')
def post(self): try: logging.debug('Foursquare push request received!') logging.debug(self.request.body) checkin = json.loads(self.request.get('checkin')) secret = self.request.get('secret') logging.debug(checkin) #verify that the secret passed matches ours hc_secret = 'VLKDNIT0XSA5FK3XIO05DAWVDVOXTSUHPE4H4WOHNIZV14G3' if hc_secret != secret: #raise an exception logging.debug('SECRETS DO NOT MATCH') #go look in our database for a matching foursquare venue id business = levr.Business.gql('WHERE foursquare_id = :1',checkin["venue"]["id"]).get() #business = levr.Business.get('ahFzfmxldnItcHJvZHVjdGlvbnIQCxIIQnVzaW5lc3MY-dIBDA') user = levr.Customer.gql('WHERE foursquare_id = :1',int(checkin['user']['id'])).get() #initialize the response object - these are defaults contentID = levr.create_content_id('foursquare') levr_url = 'http://www.levr.com/mobile/'+contentID #search for expired offers at that business #q_expired = levr.Deal.gql('WHERE businessID=:1 AND deal_status=:2',business) if business: #business found - CURRENTLY ONLY REPLYING AT BUSINESSES THAT ARE IN OUR DATABASE #for deal in levr.Deal.all().filter('businessID =', str(business.key())).run(): q = levr.Deal.gql("WHERE businessID = :1 AND deal_status = :2 ORDER BY count_redeemed DESC",str(business.key()),'active') deal = None for d in q: if d.origin != 'foursquare': deal = d text = 'Click to view the most popular offer here: '+ deal.deal_text action='deal' break else: text = "See any deals? Pay it forward! Click to add." action = 'upload' deal = None # # # numdeals = q.count() # if numdeals > 0: #many deals found # deal_matched = False # text = "See any deals? Pay it forward! Click to add." # action = 'upload' # while deal_matched == False: # deal = q.get() # if deal.origin != 'foursquare': # text = 'Click to view the most popular offer here: '+ deal.deal_text # action='deal' # deal_matched = True # else: #no deals found # text = "See any deals? Pay it forward! Click to add." # action = 'upload' #create floating_content entity and put floating_content = levr.FloatingContent( action=action, origin='foursquare', contentID=contentID, user=user, deal=deal, business=business ) floating_content.put() try: #track event via mixpanel (asynchronous) properties = { 'time' : time.time(), 'distinct_id' : enc.encrypt_key(user.key()), 'mp_name_tag' : user.display_name, 'action' : action } mp_track.track('Foursquare checkin reply',"ab1137787f393161bd481e2756b77850",properties) user_props = { '$first_name' : user.first_name, '$last_name' : user.last_name, '$email' : user.email } mp_track.person(enc.encrypt_key(user.key()),"ab1137787f393161bd481e2756b77850",user_props) to_increment = { "Checkins Served" : 1 } if action == 'deal': to_increment.update({'Deals Served':1}) elif action == 'upload': to_increment.update({'Uploads Prompted':1}) mp_track.increment(enc.encrypt_key(user.key()),"ab1137787f393161bd481e2756b77850",to_increment) except: levr.log_error() reply = { 'CHECKIN_ID' :checkin['id'], 'text' :text, 'url' :levr_url, 'contentId' :contentID } '''else: #no business found #ask pat for all the deals within walking distance url = 'http://www.levr.com/phone' ll = str(checkin['venue']['location']['lat'])+','+str(checkin['venue']['location']['lng']) request_point = levr.geo_converter(ll) precision = 6 results = levr_utils.get_deals_in_area(['all'],request_point,precision) if len(results) > 0: reply['text'] = "There are "+str(len(results))+" deals near you - click to view." reply['url'] = '' #deeplink into deal upload screen else: reply['text'] = "See any deals? Pay it forward: click to upload." reply['url'] = '' #deeplink into deal upload screen''' #reply['CHECKIN_ID'] = checkin['id'] #reply['text'] = 'Hey ethan. click here to see this reply inside Levr.' #reply['url'] = 'fsq+unhlif5eyxsklx50dasz2pqbge2hdoik5gxbwcirc55nmq4c+reply://?contentId=abcdefg12345&fsqCallback=foursquare://checkins/'+checkin['id'] #reply['url'] = 'fsq+unhlif5eyxsklx50dasz2pqbge2hdoik5gxbwcirc55nmq4c+reply://?contentId=abcdefg12345' #reply['url'] = 'http://www.levr.com?contentId=abcdefg12345' #reply['url'] = 'http://www.levr.com/deal/blah' #reply['contentId'] = 'abcdefg12345' url = 'https://api.foursquare.com/v2/checkins/'+checkin['id']+'/reply?v=20120920&oauth_token='+user.foursquare_token #url = 'https://api.foursquare.com/v2/checkins/'+reply['CHECKIN_ID']+'/reply?v=20120920&text=hitherehello&url=foursquare%2Bunhlif5eyxsklx50dasz2pqbge2hdoik5gxbwcirc55nmq4c%2Breply%3A//%3FcontentId%3Dabcdefg12345&contentId=abcdefg12345&oauth_token='+'PZVIKS4EH5IFBJX1GH5TUFYAA3Z5EX55QBJOE3YDXKNVYESZ' logging.debug(url) #result = urlfetch.fetch(url=url,method=urlfetch.POST) result = urlfetch.fetch(url=url, payload=urllib.urlencode(reply), method=urlfetch.POST) logging.debug(levr.log_dict(result.__dict__)) else: logging.info('BUSINESS NOT FOUND') except: levr.log_error() self.reponse.out.write('Could not connect with Foursquare')
def get(self): try: logging.debug('Hit the Authorize Complete Handler') client_id = 'UNHLIF5EYXSKLX50DASZ2PQBGE2HDOIK5GXBWCIRC55NMQ4C' secret = 'VLKDNIT0XSA5FK3XIO05DAWVDVOXTSUHPE4H4WOHNIZV14G3' redirect = 'https://levr-production.appspot.com/foursquare/authorize/complete' try: logging.info(levr.log_dir(self.request)) except: logging.info(self.request) code = self.request.get('code', None) #if no code was passed, then the authorization is happening through the phone. NO_CODE_MESSAGE = 'Code was not passed. Authorization is happening on phone.' assert code, NO_CODE_MESSAGE logging.info(code) #make request for token url = "https://foursquare.com/oauth2/access_token?client_id=" + client_id + "&client_secret=" + secret + "&grant_type=authorization_code&redirect_uri=" + redirect + "&code=" + code result = urlfetch.fetch(url=url) logging.debug(result.content) foursquare_token = json.loads(result.content)['access_token'] logging.info(foursquare_token) # #grab more user details # url = 'https://api.foursquare.com/v2/users/self?v=20120920&oauth_token='+token # result = urlfetch.fetch(url=url) # response_dict = json.loads(result.content) # # logging.debug(levr.log_dict(response_dict)) #let the foursquare parsing code do its thing user = social.Foursquare(foursquare_token=foursquare_token) user, new_details, new_friends = user.first_time_connect( foursquare_token=foursquare_token) # user.connect_with_content(response_dict,True,foursquare_token=token) logging.debug(levr.log_model_props(user)) logging.debug(levr.log_dict(new_details)) logging.debug(levr.log_dict(new_friends)) #send the founders a text levr.text_notify(user.first_name + ' ' + user.last_name + ' from foursquare') #launch the jinja environment jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) #set up the jinja template and echo out template = jinja_environment.get_template('templates/landing.html') self.response.out.write(template.render()) logging.debug(levr.log_dict(user)) except AssertionError, e: if e.message == NO_CODE_MESSAGE: #this is an expected case. Authorization is happening on the phone self.response.out.write('Please wait...') else: levr.log_error(e) self.response.out.write('Could not connect with Foursquare.')
def get(self): # data = mixmap.grab('Last Login',100000,'0bff6b03e7955b8e1df08a8ec0828c9f','06a9d35b90bc1a1b8035394cd295faff') days = self.request.get('days',0) start_date = date.today()-timedelta(days=int(days)) api = mixpanel.Mixpanel(api_key='0bff6b03e7955b8e1df08a8ec0828c9f',api_secret='06a9d35b90bc1a1b8035394cd295faff') # data = api.request(['segmentation'], { # 'event' : 'Search', # 'from_date' : start_date.isoformat(), # 'to_date' : date.today().isoformat(), # 'on' : 'properties["Location"]', # 'where' : 'properties["Expanded"] == boolean("false")' # }) #how many signups in the date range? data = api.request(['segmentation'], { 'event' : 'Signup Success', 'from_date' : start_date.isoformat(), 'to_date' : date.today().isoformat() }) signups = sum(data['data']['values']['Signup Success'].values()) logging.info("Signups: "+str(signups)) #how many searches in the date range? data = api.request(['segmentation'], { 'event' : 'Search', 'from_date' : start_date.isoformat(), 'to_date' : date.today().isoformat() }) searches = sum(data['data']['values']['Search'].values()) logging.info("Searches: "+str(searches)) #how many non-expanded searches in the date range? data = api.request(['segmentation'], { 'event' : 'Search', 'from_date' : start_date.isoformat(), 'to_date' : date.today().isoformat(), 'where' : 'properties["Expanded"] == boolean("false")' }) searches_non_exp = sum(data['data']['values']['Search'].values()) logging.info("Non-expanded searches: "+str(searches_non_exp)) #how many deal uploads in the date range? data = api.request(['segmentation'], { 'event' : 'Share Done', 'from_date' : start_date.isoformat(), 'to_date' : date.today().isoformat() }) uploads = sum(data['data']['values']['Share Done'].values()) logging.info("Deals uploaded: "+str(uploads)) #how many daily active users? #grab all the users data = api.request(['engage'],{}) #take only those that actually have a last seen property users = [x for x in data['results'] if '$last_seen' in x['$properties']] now = datetime.now() t_daily = now - timedelta(days=1) t_monthly = now - timedelta(days=30) daily = [x for x in users if datetime.strptime(x['$properties']['$last_seen'],'%Y-%m-%dT%H:%M:%S') > t_daily] monthly = [x for x in users if datetime.strptime(x['$properties']['$last_seen'],'%Y-%m-%dT%H:%M:%S') > t_monthly] dau_mau = float(len(daily))/float(len(monthly))*100 template_values = { "signups" : signups, "searches" : searches, "searches_non_exp" : searches_non_exp, "uploads" : uploads, "dau_mau" : "%.2f" % dau_mau, "daily" : len(daily), "monthly" : len(monthly) } logging.info(log_dict(template_values)) #launch the jinja environment jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) template = jinja_environment.get_template('templates/analytics.html') self.response.out.write(template.render(template_values))
def update_user_details(self, content=None): ''' Foursqaure Grabs the users personal information from foursquare and updates the user if content is passed, it should be the user dict responded by foursquare ''' logging.debug('\n\n FOURSQUARE UPDATE USER DETAILS PREFETCH \n\n') #get foursquare details if not content: logging.debug('USER CONTENT WAS NOT PASSED... fetch data') foursquare_response = self.fetch('') content = foursquare_response['response']['user'] else: logging.debug('USER CONTENT WAS PASSED... do not fetch data') pass logging.debug('\n\n FOURSQUARE UPDATE USER DETAILS POSTFETCH \n\n') # logging.debug(foursquare_response) logging.debug(levr.log_dict(content)) logging.debug(type(content)) #give preference to facebook and twitter info over foursquare info #grab stuff updated = {} #update the users foursquare_id foursquare_id = int(content.get('id', None)) assert foursquare_id, "foursquare_id was not retrieved" if not self.user.foursquare_id: self.user.foursquare_id = foursquare_id updated['foursquare_id'] = foursquare_id #update the rest of the users properties if not self.user.facebook_connected and not self.user.twitter_connected: # vals = { # 'first_name' : content['firstName'], # 'last_name' : content['lastName'], # 'display_name' : self.build_display_name(first_name, last_name), # 'photo' : content['photo']['prefix'] + '500x500' + content['photo']['suffix'], # 'email' : content['contact']['email'], # 'foursquare_id' : int(content['id']) # # } first_name = content.get('firstName', '') #content['firstName'] last_name = content.get('lastName', '') #content['lastName'] display_name = self.build_display_name(first_name, last_name) photo = content.get('photo', None) if photo: photo = photo.get('prefix', '') + '500x500' + photo.get( 'suffix', '') # photo = content['photo']['prefix'] + '500x500' + content['photo']['suffix'] contact = content.get('contact', None) if contact: email = contact.get('email') # email = content['contact']['email'] if not self.user.first_name: self.user.first_name = first_name updated['first_name'] = first_name if not self.user.last_name: self.user.last_name = last_name updated['last_name'] = last_name if not self.user.display_name: self.user.display_name = display_name updated['display_name'] = display_name # if not self.user.photo: #keep photo up to date self.user.photo = photo updated['photo'] = photo #grab email if not self.user.email: self.user.email = email updated['email'] = email logging.debug(levr.log_model_props(self.user)) else: # raise Exception('user has already connected with facebook or twitter') logging.info('user has already connected with facebook or twitter') return updated
def get(self): try: logging.debug('Hit the Authorize Complete Handler') client_id = facebook_auth['client_id'] client_secret = facebook_auth['client_secret'] #======================================================================= # Fetch access_token from facebook #======================================================================= #check for error error = self.request.get('error', None) assert error == None, 'User denied request' state = self.request.get('state', None) code = self.request.get('code', None) logging.debug(state) logging.debug(code) redirect_uri = 'http://levr-production.appspot.com/facebook/authorize/complete' url = 'https://graph.facebook.com/oauth/access_token?client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}'.format( client_id=client_id, redirect_uri=redirect_uri, client_secret=client_secret, code=code) # Fetch the access token from facebook result = urlfetch.fetch(url=url) logging.debug(result.content) logging.debug(type(result.content)) logging.debug(levr.log_dir(result.content)) facebook_token = result.content.split('&')[0].split('=')[1] logging.debug(facebook_token) #======================================================================= # Create User and connect them with levr #======================================================================= #wrap the user in the social class - creates new user if user doesnt exist user = social.Facebook(facebook_token=facebook_token) user, new_details, new_friends = user.first_time_connect( facebook_token=facebook_token) logging.debug(levr.log_model_props(user)) logging.debug(levr.log_dict(new_details)) logging.debug(levr.log_dict(new_friends)) try: logging.debug(user.display_name) logging.debug(user.first_name) logging.debug(user.last_name) logging.debug(user.facebook_id) except: levr.log_error() #send the founders a text levr.text_notify(user.first_name + ' ' + user.last_name + ' from facebook') #set up the jinja template and echo out # template = jinja_environment.get_template('templates/deal.html') # self.response.out.write(template.render(template_values)) self.response.out.write('Hooray! you are connected with levr!') logging.debug(levr.log_dict(user)) except: levr.log_error() self.response.out.write('Could not connect with Facebook')
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): #@UnusedVariable ''' inputs: lat,lon,limit, query response:{ [string,string] } /api/search/all? lat=42.357632 &lon=-71.089432 &limit=50 &offset=0 &uid=tAvwdQhJqgEn8hL7fD1phb9z_c-GNGaQXr0fO3GJdErv19TaoeLGNiu51St9sfoYChA= &levrToken=7ALUawsTs1R3_z_pK0YTx4cCkpfSFzuDCOM1XQCXWDM &latitudeHalfDelta=0.023277 &longitudeHalfDelta=0.027466 ''' try: tstart = datetime.now() logging.debug('SEARCH BY QUERY \n\n\n') # logging.debug(kwargs) #GET PARAMS logging.info(kwargs) #assert False geo_point = kwargs.get('geoPoint') # radius = kwargs.get('radius') # limit = kwargs.get('limit') query = kwargs.get('query', 'all') development = kwargs.get('development', False) user = kwargs.get('actor') lon_half_delta = kwargs.get('longitudeHalfDelta', 0) # lat_half_delta = kwargs.get('latitudeHalfDelta') try: logging.info(user.display_name) except: logging.info('unkown user') times = {} search = api_utils.Search(development, user) # calc precision precision = search.calc_precision_from_half_deltas( geo_point, lon_half_delta) # create ghashes ghash_list = search.create_ghash_list(geo_point, precision) # calc bounding box bounding_box = search.calc_bounding_box(ghash_list) # fetch all deals in the ghash range t1 = datetime.now() deals = search.fetch_deals(ghash_list) times.update({'fetch_deals_time': str(datetime.now() - t1)}) # filter deals by search query t1 = datetime.now() num_results, accepted_deals = search.filter_deals_by_query( deals, query) times.update({'filter_deals_time': str(datetime.now() - t1)}) # increment deal views on levr deals search.add_deal_views(deals) # init package time if query != 'all' and accepted_deals.__len__() != 0: t1 = datetime.now() packaged_deals = search.sort_and_package(accepted_deals) package_time = datetime.now() - t1 else: # act like a search all, use all deals # decompose deals by origin levr_deals, foursquare_deals = search.filter_deals_by_origin( deals) if levr_deals.__len__() > 5: t1 = datetime.now() packaged_deals = search.sort_and_package(levr_deals) package_time = datetime.now() - t1 # qualify search results. do we need more? else: t1 = datetime.now() packaged_deals = search.sort_and_package(deals) package_time = datetime.now() - t1 # add foursquare deals if foursquare_deals.__len__() < 5: # search for more foursquare deals try: # grab search information token = search.foursquare_token deal_status = search.deal_status foursquare_ids = search.get_foursquare_ids(deals) # make remote call to foursquare ft1 = datetime.now() new_foursquare_deals = api_utils.search_foursquare( geo_point, token, deal_status, foursquare_ids) times.update({ 'foursquare_search_time': str(datetime.now() - ft1) }) # add new foursquare deals packaged_deals.extend(new_foursquare_deals) except: levr.log_error( 'Error in foursquare call or parsing.') times.update({'package_time': package_time}) # else: # params = { # 'lat' : geo_point.lat, # 'lon' : geo_point.lon, # 'token' : token, # 'foursquare_ids': foursquare_ids, # 'deal_status' : deal_status # } # # logging.debug('Sending this to the task: ' + json.dumps(params)) # # #start the task # taskqueue.add(url='/tasks/searchFoursquareTask',payload=json.dumps(params)) times.update({'total_time': datetime.now() - tstart}) #=================================================================== # Send response #=================================================================== logging.info(levr.log_dict(times)) times = {key: str(times[key]) for key in times} response = { 'searchPoint': str(geo_point), 'numResults': num_results, 'boundingBox': bounding_box, # 'ending_hashes' : list(searched_hash_set), 'num_total_results': packaged_deals.__len__(), 'deals': packaged_deals, 'times': times } try: response.update( {'user': api_utils.package_user(self.user, True, False)}) except: logging.info('user not passed') # assert False, response self.send_response(response) except: levr.log_error() self.send_error()
def get(self): try: logging.debug('Hit the Authorize Complete Handler') client_id = 'UNHLIF5EYXSKLX50DASZ2PQBGE2HDOIK5GXBWCIRC55NMQ4C' secret = 'VLKDNIT0XSA5FK3XIO05DAWVDVOXTSUHPE4H4WOHNIZV14G3' redirect = 'https://levr-production.appspot.com/foursquare/authorize/complete' try: logging.info(levr.log_dir(self.request)) except: logging.info(self.request) code = self.request.get('code',None) #if no code was passed, then the authorization is happening through the phone. NO_CODE_MESSAGE = 'Code was not passed. Authorization is happening on phone.' assert code, NO_CODE_MESSAGE logging.info(code) #make request for token url = "https://foursquare.com/oauth2/access_token?client_id="+client_id+"&client_secret="+secret+"&grant_type=authorization_code&redirect_uri="+redirect+"&code="+code result = urlfetch.fetch(url=url) logging.debug(result.content) foursquare_token = json.loads(result.content)['access_token'] logging.info(foursquare_token) # #grab more user details # url = 'https://api.foursquare.com/v2/users/self?v=20120920&oauth_token='+token # result = urlfetch.fetch(url=url) # response_dict = json.loads(result.content) # # logging.debug(levr.log_dict(response_dict)) #let the foursquare parsing code do its thing user = social.Foursquare(foursquare_token=foursquare_token) user,new_details,new_friends = user.first_time_connect( foursquare_token = foursquare_token ) # user.connect_with_content(response_dict,True,foursquare_token=token) logging.debug(levr.log_model_props(user)) logging.debug(levr.log_dict(new_details)) logging.debug(levr.log_dict(new_friends)) #send the founders a text levr.text_notify(user.first_name + ' ' + user.last_name + ' from foursquare') #launch the jinja environment jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) #set up the jinja template and echo out template = jinja_environment.get_template('templates/landing.html') self.response.out.write(template.render()) logging.debug(levr.log_dict(user)) except AssertionError,e: if e.message == NO_CODE_MESSAGE: #this is an expected case. Authorization is happening on the phone self.response.out.write('Please wait...') else: levr.log_error(e) self.response.out.write('Could not connect with Foursquare.')
def get(self): # data = mixmap.grab('Last Login',100000,'0bff6b03e7955b8e1df08a8ec0828c9f','06a9d35b90bc1a1b8035394cd295faff') days = self.request.get('days', 0) start_date = date.today() - timedelta(days=int(days)) api = mixpanel.Mixpanel(api_key='0bff6b03e7955b8e1df08a8ec0828c9f', api_secret='06a9d35b90bc1a1b8035394cd295faff') # data = api.request(['segmentation'], { # 'event' : 'Search', # 'from_date' : start_date.isoformat(), # 'to_date' : date.today().isoformat(), # 'on' : 'properties["Location"]', # 'where' : 'properties["Expanded"] == boolean("false")' # }) #how many signups in the date range? data = api.request( ['segmentation'], { 'event': 'Signup Success', 'from_date': start_date.isoformat(), 'to_date': date.today().isoformat() }) signups = sum(data['data']['values']['Signup Success'].values()) logging.info("Signups: " + str(signups)) #how many searches in the date range? data = api.request( ['segmentation'], { 'event': 'Search', 'from_date': start_date.isoformat(), 'to_date': date.today().isoformat() }) searches = sum(data['data']['values']['Search'].values()) logging.info("Searches: " + str(searches)) #how many non-expanded searches in the date range? data = api.request( ['segmentation'], { 'event': 'Search', 'from_date': start_date.isoformat(), 'to_date': date.today().isoformat(), 'where': 'properties["Expanded"] == boolean("false")' }) searches_non_exp = sum(data['data']['values']['Search'].values()) logging.info("Non-expanded searches: " + str(searches_non_exp)) #how many deal uploads in the date range? data = api.request( ['segmentation'], { 'event': 'Share Done', 'from_date': start_date.isoformat(), 'to_date': date.today().isoformat() }) uploads = sum(data['data']['values']['Share Done'].values()) logging.info("Deals uploaded: " + str(uploads)) #how many daily active users? #grab all the users data = api.request(['engage'], {}) #take only those that actually have a last seen property users = [ x for x in data['results'] if '$last_seen' in x['$properties'] ] now = datetime.now() t_daily = now - timedelta(days=1) t_monthly = now - timedelta(days=30) daily = [ x for x in users if datetime.strptime( x['$properties']['$last_seen'], '%Y-%m-%dT%H:%M:%S') > t_daily ] monthly = [ x for x in users if datetime.strptime(x['$properties']['$last_seen'], '%Y-%m-%dT%H:%M:%S') > t_monthly ] dau_mau = float(len(daily)) / float(len(monthly)) * 100 template_values = { "signups": signups, "searches": searches, "searches_non_exp": searches_non_exp, "uploads": uploads, "dau_mau": "%.2f" % dau_mau, "daily": len(daily), "monthly": len(monthly) } logging.info(log_dict(template_values)) #launch the jinja environment jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) template = jinja_environment.get_template('templates/analytics.html') self.response.out.write(template.render(template_values))
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))