def post(self): '''Resets password on the database''' try: password1 = self.request.get('newPassword1') password2 = self.request.get('newPassword2') uid = self.request.get('id') uid = enc.decrypt_key(uid) if password1 == password2: #passwords match logging.debug('flag password success') encrypted_password = enc.encrypt_password(password1) logging.debug(uid) owner = levr.BusinessOwner.get(uid) owner.pw = encrypted_password owner.put() #log user in and redirect them to merchants/manage session = get_current_session() session['ownerID'] = enc.encrypt_key(owner.key())#business.key()) session['loggedIn'] = True session['validated'] = owner.validated self.redirect('/merchants/manage') else: #passwords do not match self.redirect('/merchants/password/reset?id=%s&success=False' % enc.encrypt_key(uid)) except: levr.log_error()
def get(self, *args, **kwargs): try: #grab the content ID contentID = args[0] #contentID = self.request.get('contentID') logging.debug('ContentID: ' + contentID) #uhh wtf do i do? floating_content = levr.FloatingContent.gql( 'WHERE contentID=:1', contentID).get() logging.info(floating_content.action) if floating_content.action == 'upload': user = floating_content.user #write out upload template template = jinja_environment.get_template( 'templates/mobileupload.html') template_values = { 'uid': enc.encrypt_key(str(floating_content.user.key())), 'businessID': enc.encrypt_key(str(floating_content.business.key())), 'upload_url': blobstore.create_upload_url('/mobile/upload') } logging.debug(template_values) # upload_url = blobstore.create_upload_url('/mobile/upload') # # self.response.out.write('<html><body>') # self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) # self.response.out.write('Business ID: <input name="businessID" value="%s">' % enc.encrypt_key(str(floating_content.business.key()))) # self.response.out.write('uid: <input name="uid" value="%s">' % enc.encrypt_key(str(floating_content.user.key()))) # self.response.out.write('''Upload File: <input type="file" name="img"><br> <input type="submit" # name="submit" value="Create!"> </form></body></html>''') elif floating_content.action == 'deal': #write out deal template template = jinja_environment.get_template( 'templates/mobiledealview.html') template_values = { 'uid': enc.encrypt_key(str(floating_content.user.key())), 'deal': api_utils.package_deal(floating_content.deal), 'user_agent': check_user_agent(self) } self.response.out.write(template.render(template_values)) except: levr.log_error()
def get(self, identifier): try: logging.debug(identifier) deal = levr.Deal.all().filter('share_id =', identifier).get() if deal: logging.debug(deal) ninjaKey = deal.key().parent() ninja = levr.Customer.get(ninjaKey) #CHANGE THIS: #enc_key = enc.encrypt_key(str(deal.key())) enc_key = enc.encrypt_key(str(deal.key())) template_values = { 'deal': api_utils.package_deal(deal), 'ninja': ninja.display_name, 'lat': deal.geo_point.lat, 'lon': deal.geo_point.lon, 'enc_key': enc_key } logging.debug(template_values) logging.debug(deal.__str__()) template = jinja_environment.get_template( 'templates/share.html') self.response.out.write(template.render(template_values)) else: template = jinja_environment.get_template( 'templates/shareError.html') self.response.out.write(template.render()) except: levr.log_error()
def post(self,*args,**kwargs): try: #RESTRICTED logging.debug('CONNECT TWITTER\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') twitter_token = kwargs.get('remoteToken') twitter_token_secret = kwargs.get('remoteTokenSecret') twitter_id = kwargs.get('remoteID') # development = kwargs.get('development') user = social.Twitter(user,'verbose') 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(e) assert False, 'Could not connect with foursquare. '.format('') #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)
def get(self): cor = levr.CashOutRequest.gql('WHERE status=:1 ORDER BY amount DESC','pending').get() if cor: ninja = levr.Customer.get(cor.key().parent()) #count the number of deals from this person q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1',ninja.key()) numDeals = q.count() cor.money_available_paytime = ninja.money_available cor.put() template_values = { "corID" : enc.encrypt_key(cor.key().__str__()), "amount" : cor.amount, "money_available_paytime" : cor.money_available_paytime, "life_paid" : ninja.money_paid, "numDeals" : numDeals } template = jinja_environment.get_template('templates/payments.html') self.response.out.write(template.render(template_values)) else: self.response.out.write('No cash-out-requests')
def get(self): cor = levr.CashOutRequest.gql('WHERE status=:1 ORDER BY amount DESC', 'pending').get() if cor: ninja = levr.Customer.get(cor.key().parent()) #count the number of deals from this person q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1', ninja.key()) numDeals = q.count() cor.money_available_paytime = ninja.money_available cor.put() template_values = { "corID": enc.encrypt_key(cor.key().__str__()), "amount": cor.amount, "money_available_paytime": cor.money_available_paytime, "life_paid": ninja.money_paid, "numDeals": numDeals } template = jinja_environment.get_template( 'templates/payments.html') self.response.out.write(template.render(template_values)) else: self.response.out.write('No cash-out-requests')
def get(self): '''The page where they view info about the widget''' try: headerData = levr_utils.loginCheck(self, True) logging.debug(headerData) ownerID = headerData['ownerID'] ownerID = enc.decrypt_key(ownerID) #business info business = levr.Business.all().filter('owner = ',db.Key(ownerID)).get() logging.debug(business) #businessID businessID = enc.encrypt_key(business.key()) #iframe frame = "<iframe src='"+levr_utils.URL+"/widget?id="+business.widget_id+"' frameborder='0' width='1000' height='400' >Your Widget</iframe> />" # frame = "<iframe src='/widget?id="+business.widget_id+"' frameborder='0' width='1000' height='400' >Your Widget</iframe>" logging.debug(frame) template_values = { 'business' : business, 'businessID' : businessID, 'frame' : frame } template = jinja_environment.get_template('templates/manageWidget.html') self.response.out.write(template.render(template_values)) except: levr.log_error()
def post(self): '''input:user email output: success, sends email to email account''' try: user_email = self.request.get('email') user = levr.Customer.gql('WHERE email=:1',user_email).get() logging.debug(user) if not user: logging.debug('flag not user') #redirect self.redirect('/password/lost?success=False') else: logging.debug('flag is user') #send mail to the admins to notify of new pending deal url ='http://getlevr.appspot.com/password/reset?id=' + enc.encrypt_key(user.key()) logging.info(url) try: mail.send_mail(sender="Lost Password<*****@*****.**>", to="Patrick Walsh <*****@*****.**>", subject="New pending deal", body=""" Follow this link to reset your password: %s """ % url).send() sent = True except: sent = False logging.error('mail not sent') template_values={"sent":sent} jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) template = jinja_environment.get_template('templates/lostPasswordEmailSent.html') self.response.out.write(template.render(template_values)) except: levr.log_error()
def post(self, *args, **kwargs): try: #RESTRICTED logging.debug('CONNECT TWITTER\n\n\n') logging.debug(kwargs) user = kwargs.get('actor') twitter_token = kwargs.get('remoteToken') twitter_token_secret = kwargs.get('remoteTokenSecret') twitter_id = kwargs.get('remoteID') # development = kwargs.get('development') user = social.Twitter(user, 'verbose') 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(e) assert False, 'Could not connect with foursquare. '.format('') #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)
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)
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)
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)
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)
def get(self,*args,**kwargs): try: #grab the content ID contentID = args[0] #contentID = self.request.get('contentID') logging.debug('ContentID: ' + contentID) #uhh wtf do i do? floating_content = levr.FloatingContent.gql('WHERE contentID=:1',contentID).get() logging.info(floating_content.action) if floating_content.action == 'upload': user = floating_content.user #write out upload template template = jinja_environment.get_template('templates/mobileupload.html') template_values = { 'uid':enc.encrypt_key(str(floating_content.user.key())), 'businessID':enc.encrypt_key(str(floating_content.business.key())), 'upload_url':blobstore.create_upload_url('/mobile/upload') } logging.debug(template_values) # upload_url = blobstore.create_upload_url('/mobile/upload') # # self.response.out.write('<html><body>') # self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) # self.response.out.write('Business ID: <input name="businessID" value="%s">' % enc.encrypt_key(str(floating_content.business.key()))) # self.response.out.write('uid: <input name="uid" value="%s">' % enc.encrypt_key(str(floating_content.user.key()))) # self.response.out.write('''Upload File: <input type="file" name="img"><br> <input type="submit" # name="submit" value="Create!"> </form></body></html>''') elif floating_content.action == 'deal': #write out deal template template = jinja_environment.get_template('templates/mobiledealview.html') template_values = { 'uid':enc.encrypt_key(str(floating_content.user.key())), 'deal': api_utils.package_deal(floating_content.deal), 'user_agent': check_user_agent(self) } self.response.out.write(template.render(template_values)) except: levr.log_error()
def loginCustomer(email_or_owner,pw): '''This is passed either an email or a username, so check both''' logging.info(pw) pw = enc.encrypt_password(pw) logging.info(pw) logging.info(email_or_owner) q_email = levr.Customer.gql('WHERE email = :1 AND pw=:2',email_or_owner,pw) q_owner = levr.Customer.gql('WHERE alias = :1 AND pw=:2',email_or_owner,pw) r_email = q_email.get() r_owner = q_owner.get() if r_email != None: #found user on the basis of email #automatically update last login r_email.put() return { 'success' : True, 'data' : { 'uid' : enc.encrypt_key(r_email.key().__str__()), 'email' : r_email.email, 'userName' : r_email.alias, 'group' : r_email.group }, 'notifications' : r_email.get_notifications() } elif r_owner != None: #found user on the basis of username #automatically update last_login r_owner.put() return { 'success' : True, 'data' : { 'uid' : enc.encrypt_key(r_owner.key().__str__()), 'email' : r_owner.email, 'userName' : r_owner.alias, 'group' : r_owner.group }, 'notifications' : r_owner.get_notifications() } else: return { 'success' : False, 'error': 'Incorrect username, email, or password. Please try again!' }
def post(self): try: #this is passed when an ajax form is checking the login state email = self.request.get('email') pw = enc.encrypt_password(self.request.get('pw')) if self.request.get('type') == 'ajax': logging.debug('AJAX CHECK') #check if login is valid q = levr.BusinessOwner.gql('WHERE email =:1 AND pw =:2', email, pw) if q.get(): #echo that login was successful self.response.out.write(True) else: #echo that login was not successful self.response.out.write(False) else: #Normal login attempt. Redirects to manage or the login page email = self.request.get('email') # email = db.Email(email) pw = enc.encrypt_password(self.request.get('pw')) logging.debug(email) logging.debug(pw) if email == None: email = '' if pw == None: pw = '' #the required text fields were entered #query database for matching email and pw owner = levr.BusinessOwner.all().filter('email =', email).filter('pw =', pw).get() #search for owner logging.debug(owner) if owner != None: logging.debug('owner exists... login') #owner exists in db, and can login session = get_current_session() session['ownerID'] = enc.encrypt_key(owner.key())#business.key()) session['loggedIn'] = True session['validated'] = owner.validated self.redirect('/merchants/manage') else: #show login page again - login failed template_values = { 'success' : False, 'email' : email } template = jinja_environment.get_template('templates/login.html') self.response.out.write(template.render(template_values)) # self.response.out.write(template_values) except: levr.log_error()
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)
def post(self): logging.debug(self.request.body) owner_id = self.request.get('owner_id') owner = levr.BusinessOwner.get(owner_id) session = get_current_session() session['ownerID'] = enc.encrypt_key(owner_id)#business.key()) session['loggedIn'] = True session['validated'] = owner.validated self.redirect('/merchants/manage')
def get(self): try: #grab all the deals with current status == pending deal = levr.CustomerDeal.all().filter('been_reviewed =', False).get() #dictify deal if deal: #logging.info(deal['dateEnd']) #get the first matching entity and parse into template values logging.debug(levr_utils.log_model_props(deal)) business = levr.Business.get(deal.businessID) if not business: raise Exception('business does not exist') ninjaID = deal.key().parent() logging.debug(ninjaID) ninja = levr.Customer.get(ninjaID) #sort tags for easy readin tags = deal.tags tags.sort() template_values = { "deal" : deal, "img_big" : levr_utils.URL+'/phone/img?dealID='+enc.encrypt_key(deal.key())+'&size=dealDetail', "img_small" : levr_utils.URL+'/phone/img?dealID='+enc.encrypt_key(deal.key())+'&size=list', "tags" : tags, "business" : business, "dealID" : enc.encrypt_key(deal.key()), "businessID": enc.encrypt_key(business.key()), "ninja" : ninja } logging.debug(levr_utils.log_dict(template_values)) template = jinja_environment.get_template('templates/admin_pending.html') self.response.out.write(template.render(template_values)) else: self.response.out.write('No pending deals!') except Exception,e: levr.log_error(e) self.response.out.write('Error fetching deal. See logs.')
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)
def signupCustomer(email,alias,pw): pw = enc.encrypt_password(pw) '''Check availability of username+pass, create and login if not taken''' #check availabilities q_email = levr.Customer.gql('WHERE email = :1',email) q_alias = levr.Customer.gql('WHERE alias = :1',alias) r_email = q_email.get() r_alias = q_alias.get() if r_email == None and r_alias == None: #nothing found c = levr.Customer() c.email = email c.pw = pw c.alias = alias #generate random number to decide what split test group they are in choice = randint(10,1000) decision = choice%2 if decision == 1: group = 'paid' else: group = 'unpaid' #set a/b test group to customer entity c.group = group #put c.put() return { 'success' :True, 'uid' :enc.encrypt_key(c.key().__str__()), 'email' :email, 'userName' :alias, 'group' :group } elif r_email != None: return { 'success': False, 'field': 'email', 'error': 'That email is already registered. Try again!' } elif r_alias != None: return { 'success': False, 'field': 'alias', 'error': 'That username is already registered. Try again!' }
def post(self): try: logging.debug(self.request.headers) logging.debug(self.request.body) upload = self.get_uploads()[0] logging.debug(upload) blob_key = upload.key() #grab form data idx = int(self.request.get('index')) primary_cat = self.request.get('primary_cat') # image = self.request.get('img') # image = images.resize(image,640,160) obj = levr.EmptySetResponse.all().filter('index',idx).get() ########### need to delete existing blob logging.debug(obj) if not obj: logging.debug("NO OBJECT!~") #create new emptySetResponse obj = levr.EmptySetResponse() else: logging.debug("FLAG there is object!!!!!") #delete old blob old_blob = obj.img # logging.debug(old_blob_key) # old_blob = blobstore.BlobInfo.get(old_blob_key) # logging.debug(old_blob) old_blob.delete() # logging.debug(old_blob) obj.primary_cat = primary_cat obj.img = blob_key obj.index = idx obj.put() obj_key = enc.encrypt_key(obj.key()) logging.debug(obj_key) self.redirect('/phone/img?size=fullSize&dealID=%s' % obj_key) #url = images.get_serving_url(obj.img) # self.response.headers['Content-Type'] = 'image/png' # self.response.out.write(obj.img) # logging.info(self.request.headers) # logging.info(self.request.body) except: levr.log_error(self.request.body)
def post(self): '''input:user email output: success, sends email to email account''' try: user_email = self.request.get('email') user = levr.BusinessOwner.all().filter('email =', user_email).get() logging.debug(user) if not user: logging.debug('flag not user') self.redirect('/merchants/login?action=password&success=False') else: logging.debug('flag is user') #send mail to the admins to notify of new pending deal url = levr_utils.URL+'/merchants/password/reset?id=' + enc.encrypt_key(user.key()) logging.info(url) try: message = mail.EmailMessage( sender ="Levr <*****@*****.**>", subject ="Reset Password", to =user.email) logging.debug(message) body = 'Hello,\n\n' body += "To reset your Levr password, please follow this link.\n\n" body += url+"\n\n" body += "If you did not request this password reset, please ignore this email.\n\n" body += "Regards,\n\n" body += "The Levr Team" message.body = body message.send() logging.debug(body) logging.debug(url) # sent = True except: # sent = False logging.error('mail not sent') self.redirect('/merchants/login?action=password&success=false') #TODO: add parameter to login that shows it was not a success because the email was not sent else: # template_values={"sent":sent} self.redirect('/merchants/login?action=password&success=true') except: levr.log_error()
def get(self): try: #check login headerData = levr_utils.loginCheck(self, True) #get the owner information ownerID = headerData['ownerID'] ownerID = enc.decrypt_key(ownerID) ownerID = db.Key(ownerID) owner = levr.BusinessOwner.get(ownerID) logging.debug(owner) #get the business business = owner.businesses.get()#TODO: this will be multiple businesses later #get deal dealID = self.request.get('id') #create upload url BEFORE DECRYPTING url = '/merchants/editDeal/upload?uid=' + headerData['ownerID'] + '&business='+ enc.encrypt_key(business.key()) +'&deal=' + dealID upload_url = blobstore.create_upload_url(url) #decrypt id, get and format deal dealID = enc.decrypt_key(dealID) deal = levr.Deal.get(dealID) deal = levr.phoneFormat(deal, 'manage') template_values = { "edit" :True, "upload_url":upload_url, "deal" :deal, "owner" :owner, "business" :business, "headerData":headerData } template = jinja_environment.get_template('templates/deal.html') self.response.out.write(template.render(template_values)) except: levr.log_error()
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)
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)
def post(self): '''Resets password on the database''' password1 = self.request.get('newPassword1') password2 = self.request.get('newPassword2') uid = self.request.get('id') uid = enc.decrypt_key(uid) if password1 == password2: #passwords match logging.debug('flag password success') encrypted_password = enc.encrypt_password(password1) logging.debug(uid) user = levr.Customer.get(uid) user.pw = encrypted_password user.put() template_values={'success':'True'} jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) template = jinja_environment.get_template('templates/resetPasswordSuccess.html') self.response.out.write(template.render(template_values)) else: #passwords do not match self.redirect('/password/reset?id=%s&success=False' % enc.encrypt_key(uid))
def get(self): '''Creates a list of deal objects to put plugged into an iframe''' try: #identify the business who is requesting their deals businessID = self.request.get('id') logging.debug(businessID) businessID = enc.decrypt_key(businessID) logging.debug(businessID) #grab the deals for the business deals = levr.Deal.all().filter('businessID =', businessID).fetch(None) logging.debug(deals) if not deals: #business does not have any deals self.response.out.write('No deals!') plugs = [] else: #grab/format the necessary information for each deal plugs = [levr.phoneFormat(deal,'widget') for deal in deals] #check loginstate of user viewing the deal headerData = levr_utils.loginCheck(self,False) headerData['loggedIn'] = False # self.response.out.write(headerData) template_values = { 'headerData' : headerData, 'businessID' : enc.encrypt_key(businessID), 'deals' : plugs, } logging.debug(template_values) jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) template = jinja_environment.get_template('templates/widget.html') self.response.out.write(template.render(template_values)) except: levr.log_error()
def get(self): '''This is the deal upload page''' try: #check login headerData = levr_utils.loginCheck(self, True) logging.debug(headerData) #get the owner information ownerID = headerData['ownerID'] ownerID = enc.decrypt_key(ownerID) ownerID = db.Key(ownerID) owner = levr.BusinessOwner.get(ownerID) logging.debug(owner) #get the business business = owner.businesses.get()#TODO: this will be multiple businesses later #create tags from the business tags = business.create_tags() #create the upload url url = '/merchants/deal/upload?uid=' + headerData['ownerID'] + '&business=' + enc.encrypt_key(business.key()) logging.debug(url) upload_url = blobstore.create_upload_url(url) #consolidate the values template_values = { "tags" : tags, "upload_url" : upload_url, "deal" : None, "business" : business, #TODO need to grab multiple businesses later "owner" : owner } template = jinja_environment.get_template('templates/deal.html') self.response.out.write(template.render(template_values)) except: levr.log_error()
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 create_levr_token(): #creates a unique id than forms the levr_token token = uuid.uuid4() token = enc.encrypt_key(''.join(token.__str__().split('-'))).replace('=','') return token
def post(self): #decode the input JSON and pull out the action parameter try: decoded = json.loads(self.request.body) action = decoded["action"] logging.info(action) try: uid = enc.decrypt_key(decoded["in"]["uid"]) user = levr.Customer.get(uid) logging.debug( levr_utils.log_model_props(user, ['alias', 'email'])) except Exception, e: # logging.debug(uid) logging.debug(e) #switch action #***************signup************************************************ if action == "signup": logging.info('signup') #grab email/password from request body email = decoded["in"]["email"] alias = decoded["in"]["alias"] pw = decoded["in"]["pw"] toEcho = levr_utils.signupCustomer(email, alias, pw) #***************login************************************************* elif action == "login": logging.info('login') #grab email/password from request body email_or_owner = decoded["in"]["email_or_owner"] pw = decoded["in"]["pw"] toEcho = levr_utils.loginCustomer(email_or_owner, pw) #***************dealResults************************************************ elif action == "popularItems": logging.info('popularItems') lat = decoded['in']['latitude'] lon = decoded['in']['longitude'] request_point = levr.geo_converter(str(lat) + "," + str(lon)) #get all deals in the area deals = levr_utils.get_deals_in_area(['all'], request_point) #compile a list of all of the tags tags = [] for deal in deals: tags.extend(list(set(deal.tags))) tags.sort() logging.debug(tags) #convert list of all tags to a dict of key=tag, val=frequency count = {} for tag in tags: # logging.debug(tag in count) if tag in count: count[tag] += 1 else: count[tag] = 1 #DEBUG #convert dict of tag:freq into list of tuples tuple_list1 = [] for key in count: tuple_list1.append((count[key], key)) tuple_list1.sort() tuple_list1.reverse() logging.debug(tuple_list1) #/DEBUG #remove unwanted stuff new_count = {} for tag in count: #search occurs more than once if count[tag] > 1: #tag is not a number if tag.isdigit() == False: #tag is not in blacklist if tag not in blacklist: new_count[tag] = count[tag] # logging.debug(levr_utils.log_dict(count)) #convert dict of tag:freq into list of tuples tuple_list = [] for key in new_count: tuple_list.append((new_count[key], key)) tuple_list.sort() tuple_list.reverse() logging.debug(tuple_list) # for i in tuple_list: # logging.debug(i) #select only the most popular ones, and convert to list word_list = [x[1] for x in tuple_list] #if the popular items list is longer than 6, send entire list, else only send 6 logging.debug(word_list.__len__()) if word_list.__len__() < 6: popularItems = word_list else: popularItems = word_list[:6] data = {'popularItems': popularItems} toEcho = {'success': True, 'data': data} elif action == "dealResults": logging.info('dealResults') logging.info(decoded['in']) #grab primaryCat from the request body primaryCat = decoded["in"]["primaryCat"] #search term # start = decoded["in"]["start"] #starting index of search results #!!!not used numResults = decoded["in"]["size"] geo_point = decoded["in"]["geoPoint"] try: precision = int(decoded['in']['precision']) except: precision = 5 logging.debug(numResults) #length of search results list #should be None if we want all results #normalize search query primaryCat = primaryCat.lower() ###filter by location - get neighborhoods request_point = levr.geo_converter(geo_point) # #normalize search query primaryCat = primaryCat.lower() #otherwise, search based on the tags tags = levr.tagger(primaryCat) logging.debug(tags) #batch get results. here is where we would set the number of results we want and the offset results = levr_utils.get_deals_in_area(tags, request_point, precision) logging.info('number of deals fetched: ' + str(results.__len__())) #define an empty "dealResults" LIST, and initialize the counter to 0 #initialize isEmpty to 1 isEmpty = True dealResults = [] #iterate over the results #Want to grab deal information for each category for result in results: # logging.info('Rank: ' + str(result.rank)) #break if results limit is hit isEmpty = False #trade an object for a phone-formatted dictionary deal = levr.phoneFormat(result, 'list', primaryCat) #indicate that this is not a sentinel deal['isSentinel'] = False logging.debug(result.geo_hash) #push the whole dictionary onto a list dealResults.append(deal) #increment the counter # resultsPushed += 1 logging.debug(dealResults.__len__()) ##debug # deals = levr.Deal.all().fetch(None) # for d in deals: # logging.debug(d.geo_hash) # ############OLD # #normalize search query # primaryCat = primaryCat.lower() # # # #build search query # q = levr.Deal.all() # # logging.debug("total number of deals: "+str(q.count())) # #only active deals # q.filter('deal_status','active') # #primaryCat will be mapresults to return everything # if primaryCat == 'all': # #get all deals - no filter # logging.debug('all') # else: # logging.debug('not all') # #normalize search query # primaryCat = primaryCat.lower() # #otherwise, search based on the tags # tags = levr.tagger(primaryCat) # logging.debug(tags) # #grab all deals where primary_cat is in tags # for tag in tags: # logging.debug('tag: '+str(tag)) # q.filter('tags =',tag) # # ###filter by location # request_point = levr.geo_converter(geo_point) # request_point = levr.geo_converter('42.35,-71.110') # center_hash = geohash.encode(request_point.lat,request_point.lon,precision=6) # hash_set = geohash.expand(center_hash) # # #get keys of all corresponding deals # deal_keys = [] # for query_hash in hash_set: # q.filter('geo_hash >=',query_hash) #min bound # q.filter('geo_hash <=',query_hash+"{") #max bound # deal_keys.extend(q.fetch(None)) # # #batch get results. here is where we would set the number of results we want and the offset # results = levr.Deal.get(deal_keys) # logging.debug # #define an empty "dealResults" LIST, and initialize the counter to 0 # #initialize isEmpty to 1 # isEmpty = True # #iterate over the results # #Want to grab deal information for each category # for result in results: ## logging.info('Rank: ' + str(result.rank)) # #break if results limit is hit # isEmpty = False # #trade an object for a phone-formatted dictionary # deal = levr.phoneFormat(result,'list',primaryCat) # #indicate that this is not a sentinel # deal['isSentinel'] = False # #push the whole dictionary onto a list # dealResults.append(deal) # #increment the counter ## resultsPushed += 1 # ###########################/OLD # #if isempty is true, send back suggested searches instead # if isEmpty == False: # dealResults.append({"isSentinel":True}) # # #go get (all) suggested searches # q = levr.EmptySetResponse.all() # #sory by index # q.order('index') # #loop through and append to data # for result in q: # searchObj = {"isSentinel":False, # "primaryCat":result.primary_cat, # "imgURL": levr_utils.URL+"/phone/img?size=emptySet&dealID=" + enc.encrypt_key(result.key()) # } # #push to stack # dealResults.append(searchObj) #get notifications # ninja = levr.Customer.get(uid) # notifications = ninja.get_notifications() #add boundary lon = [ -71.13128751569184, -71.13747576487495, -71.13221920314751, -71.1315606660475, -71.1309193072284, -71.1297731686955, -71.12886527141396, -71.12773981063141, -71.12726203628873, -71.1216289071829, -71.12121164180434, -71.10497418088163, -71.1040140000405, -71.10267756839711, -71.0946922485677, -71.09243243954906, -71.09227823963506, -71.0950832349529, -71.097815779737, -71.11251814985596, -71.11356954283684, -71.11706884229781, -71.11779512636194, -71.11965434764042, -71.12212678446998, -71.12626327632834, -71.13026582412857 ] lat = [ 42.35604793867138, 42.3536306062291, 42.35301975662632, 42.35130590336475, 42.35025979303107, 42.34889896173047, 42.3474035881804, 42.34587017442897, 42.3454410032402, 42.34240376898205, 42.34200386027403, 42.34665152547006, 42.34437686280481, 42.34335156373593, 42.34544719585433, 42.34689842049458, 42.35112647889721, 42.35062769794382, 42.35071497934108, 42.35189268933054, 42.35225746246078, 42.35405913476999, 42.35424633071435, 42.35461863217454, 42.35493709975472, 42.35550741935002, 42.35597048179658 ] boundary = {"lat": lat, "lon": lon} if primaryCat == 'all': #echo back data - include boundary toEcho = { "success": True, "data": dealResults, "isEmpty": isEmpty, "boundary": boundary } #,"notifications":notifications} else: toEcho = { "success": True, "data": dealResults, "isEmpty": isEmpty } #,"notifications":notifications} #***************getUserFavs************************************************ elif action == "getUserFavs": ''' Grabs all of the favorites of a user - only data to show on list input : uid output: name, description, dealValue, dealType, imgPath, businessName, primaryCat ''' logging.info('getUserFavs') #grab inputs uid = enc.decrypt_key(decoded["in"]["uid"]) logging.debug(uid) logging.debug(decoded["in"]["uid"]) #grab user entity user = levr.Customer.get(uid) #grab list of favorties - list of deal keys favorites = user.favorites logging.debug(favorites) #batch grab favorited deals deals = levr.Deal.get(favorites) logging.debug(deals) #format deals for output to phone formatted_deals = [] for deal in deals: try: formatted_deals.append(levr.phoneFormat(deal, 'list')) except: logging.warning( 'deal exists in favorites but was removed from the db' ) logging.warning(deal) # formatted_deals = [levr.phoneFormat(deal,'list') for deal in deals] #assign formatted deals to data list that doesnt follow standards data = formatted_deals #get notifications notifications = user.get_notifications() #output toEcho = { "success": True, "data": data, 'notifications': notifications } #ADD FAVORITE*********************************************************** elif action == "addFav": ''' User pressed add favorite button = add favorite mapping input: dealID,uid,primaryCat output: success = bool ''' logging.info('addFav') #get inputs uid = enc.decrypt_key(decoded["in"]["uid"]) dealID = enc.decrypt_key(decoded["in"]["dealID"]) #get user entity user = levr.Customer.get(uid) #append dealID to favorites property user.favorites.append(db.Key(dealID)) logging.debug(user.favorites) # #get notifications notifications = user.get_notifications() #close entity user.put() #output toEcho = {"success": True, "notifications": notifications} #DELETE FAVORITE******************************************************** elif action == "delFav": ''' User presses delete favorite button - delete favorite mapping input: dealID,uid,primaryCat output: success = bool ''' logging.info('delFav') #get inputs uid = enc.decrypt_key(decoded["in"]["uid"]) dealID = enc.decrypt_key(decoded["in"]["dealID"]) deal_to_delete = db.Key(dealID) logging.debug(deal_to_delete) #get user entity user = levr.Customer.get(uid) logging.debug(levr_utils.log_model_props(user)) #grab favorites list favorites = user.favorites logging.debug(favorites) #generate new favorites list without requested dealID new_favorites = [ deal for deal in favorites if deal != deal_to_delete ] logging.debug(new_favorites) #reassign user favorites to new list user.favorites = new_favorites logging.debug(user.favorites) #get notifications notifications = user.get_notifications() #close entity user.put() toEcho = {"success": True, "notificaions": notifications} #***************getOneDeal************************************************ elif action == "getOneDeal": ''' Information to show on the deal information screen. input : primaryCat,dealID output : json object of all information necessary to describe deal ''' logging.info('getOneDeal') #grab input dealID dealID = enc.decrypt_key(decoded["in"]["dealID"]) primary_cat = decoded["in"]["primaryCat"] #fetch deal result = levr.Deal.get(dealID) #convert fetched deal into dictionary deal = levr.phoneFormat(result, 'deal') #push the primary onto the dictionary deal.update({"primaryCat": primary_cat}) #echo back success! # #get notifications # ninja = levr.Customer.get(uid) # notifications = ninja.get_notifications() toEcho = { "success": True, "data": deal } #,"notificaions":notifications} elif action == "getMyDeals": ''' returns all of the deals that were uploaded by the ninja input : uid output : list of deal objects ''' logging.info('getMyDeals') uid = enc.decrypt_key(decoded["in"]["uid"]) logging.debug("encrypted uid: " + str(decoded["in"]["uid"])) logging.debug("uid: " + str(uid)) #grab all deal children of the user deals = levr.CustomerDeal.gql( "WHERE ANCESTOR IS :1 ORDER BY date_uploaded DESC", uid).fetch(None) logging.debug(deals) #format CUSTOMER deals data = [levr.phoneFormat(x, 'myDeals') for x in deals] #I believe this will just return data:None if deals is empty #flush their notifications ninja = levr.Customer.get(uid) # ninja.flush_new_redeem_count() # ninja.put() #get new notifications notifications = ninja.get_notifications() #Grab their cash out requests, if they exist cor_q = levr.CashOutRequest.gql( "WHERE ANCESTOR IS :1 AND status=:2", uid, 'pending') cor = cor_q.get() if cor != None: notifications["isPendingCashOut"] = True else: notifications["isPendingCashOut"] = False notifications["pendingCashOutAmount"] = ninja.money_available toEcho = { "success": True, "data": data, "notifications": notifications } elif action == "getMyStats": ''' returns the user's statistics input : uid output : ''' logging.info('getMyStats') uid = enc.decrypt_key(decoded['in']['uid']) #get user information user = db.get(uid) #format user information data = user.get_stats() #get new notifications notifications = user.get_notifications() toEcho = { "success": True, "data": data, "notifications": notifications } elif action == "checkRedeem": logging.info('checkRedeem') #grab corresponding deal uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) #grab the customer customer = levr.Customer.get(uid) #new notifications? notifications = customer.get_notifications() #don't try and redeem the same deal twice. . . if str(dealID) in customer.redemptions: toEcho = { "success": False, "data": { "message": "You have already redeemed this deal." }, "notifications": notifications } else: toEcho = {"success": True, "notifications": notifications} #!!!!!!!!REMOVE THIS WHEN CHECKING IS PUT BACK IN # toEcho = {"success":True,"notifications":notifications} elif action == "getRedeemScreen": logging.info('getRedeemScreen') #grab inputs dealID = enc.decrypt_key(decoded['in']['dealID']) #grab the deal deal = levr.Deal.get(dealID) #format the deal data = levr.phoneFormat(deal, 'dealsScreen') #echo toEcho = {"success": True, "data": data} elif action == "redeem": logging.info('redeem') #grab corresponding deal uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) #grab the deal deal = levr.Deal.get(dealID) #grab the customer customer = levr.Customer.get(uid) #don't try and redeem the same deal twice. . . # if dealID in customer.redemptions: # raise Exception('Cannot redeem a deal more than once') #increment deal "redeemed" count by 1 deal.count_redeemed += 1 #add deal to "redeemed" for the customer customer.redemptions.append(dealID) ###get customer new_redemptions if they are a ninja notifications = customer.get_notifications() #update customer customer.put() #Is this a deal uploaded by a ninja? If so, do ninja things if type(deal) is levr.CustomerDeal: #update deal ninjaStats deal.gate_count = int( math.floor(deal.count_redeemed / deal.gate_requirement)) if deal.gate_count > deal.gate_max: #reset if over deal.gate_count = deal.gate_max #update deal.earned_total difference = deal.update_earned_total() #put deal deal.put() #get the ninja ninjaKey = deal.key().parent() ninja = levr.Customer.get(ninjaKey) #update the ninja's earned amount ninja.update_money_earned(difference) #update the ninja's available amount ninja.update_money_available(difference) #notify the ninja of new redemptions ninja.increment_new_redeem_count() #echo stats ninja.echo_stats() deal.echo_stats() #update ninja ninja.put() else: #deal is owned by a business - FOR THE FUTURE! logging.info('Business!') pass toEcho = {"success": True, "notifications": notifications} elif action == "cashOut": logging.info('cashOut') uid = enc.decrypt_key(decoded['in']['uid']) # uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiYAQw' #grab the ninja ninja = levr.Customer.get(uid) #delete any current cashOutRequests q = levr.CashOutRequest.gql( 'WHERE ANCESTOR IS :1 AND status=:2', ninja.key(), 'pending').fetch(None) for result in q: result.delete() #create a new cashOut request cor = levr.CashOutRequest(parent=ninja) cor.amount = ninja.money_available cor.money_available_paytime = cor.amount #get notifications notifications = ninja.get_notifications() if cor.amount == 0: toEcho = { "success": False, "data": { "message": "You need to earn something before you can cash out!", "notifications": notifications } } else: cor.status = 'pending' cor.date_created = datetime.now() cor.put() toEcho = {"success": True, "notifications": notifications} ## ====== SPOOF ACCEPTANCE FOR BETA TEST ====== ## logging.debug(levr_utils.log_model_props(ninja)) logging.debug(levr_utils.log_model_props(cor)) #get corID #get cor #get the larger amount if money available at paytime is different if cor.amount != cor.money_available_paytime: amount = cor.money_available_paytime cor.note = 'The money available at paytime was greater than when the COR was created, so the paytime balance was used.' else: amount = cor.amount #get payment email receiver_email = ninja.email #set cor to "paid" cor.status = "paid" cor.date_paid = datetime.now() cor.payKey = 'this is a pay key' cor.put() #for each deal, make paid_out == earned_total q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1', ninja.key()) for deal in q: deal.paid_out = deal.earned_total deal.put() #are number consistent? logging.debug(cor.amount) logging.debug(cor.money_available_paytime) if cor.amount != cor.money_available_paytime: #remember to encrypt the key if this is being used for anything #other than just error logging logging.error('PAY MISMATCH AT UID:' + ninja.key().__str__()) #send email here later #set ninja money_available back to 0 ninja.money_available = 0.0 #increment money_paid for the customer ninja.money_paid += amount #update ninja ninja.put() logging.info('Payment completed!') logging.debug(levr_utils.log_model_props(ninja)) logging.debug(levr_utils.log_model_props(cor)) #send email to the ninja confirming their cashout! message = mail.EmailMessage(sender="LEVR <*****@*****.**>", subject="Levr Cash Out", to=receiver_email) logging.debug(message) body = 'Hey Beta Tester,\n\n' body += "You submitted a request to be paid for uploading deals to the Levr platform.\n\n" body += "If this were real life, this email would be letting you know that you were about to be paid via paypal an amount of $" + str( amount) + ". " body += "Unfortunately your reality is being simulated. " body += "\n\nThanks for helping us test.\nSincerely,\nThe Levr Team" # #alt body for when not in beta # message = mail.EmailMessage( # sender ="LEVR <*****@*****.**>", # subject ="Levr Cash Out", # to =receiver_email) # body = 'Hey '+ninja.alias+',\n\n' # body += "You have submitted a request to be paid for the deals that you've uploaded to Levr.\n\n" # body += "The amount you have requested is: $"+str(amount)+".\n\n" # body += "Your request is in the process of being reviewed. If accepted, we will send you an email with instructions to receive your payment via PayPal." # body += "\n\nSincerely,\nThe Levr Team" # message.body = body # logging.debug(body) # message.send() # elif action == "getTargetedBusinesses": #get businesses that have property targeted = True logging.info('getTargetedBusinesses') businesses = levr.Business.all().filter( 'targeted =', True).order('-business_name').fetch(None) data = {'targetedBusinesses': []} for business in businesses: data['targetedBusinesses'].append({ "businessName": business.business_name, "geoPoint": str(business.geo_point), "vicinity": business.vicinity, "businessID": enc.encrypt_key(business.key()) }) toEcho = {"success": True, "data": data} elif action == "fetchUploadURL": logging.info('fetchUploadURL') upload_url = blobstore.create_upload_url('/phone/uploadDeal') logging.debug(upload_url) toEcho = {"success": True, "data": {"url": upload_url}} elif action == "checkBounty": logging.info('fetchUploadURL') where = "College campuses in Boston, MA" what = "Offers on food, drink, clothing, and entertainment" toEcho = { "success": True, "data": { "where": where, "what": what } } elif action == "reportDeal": #user reports a deal logging.info('reportDeal') uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) # uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiRAQw' # dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghCdXNpbmVzcxiTAQwLEgREZWFsGJQBDA' # dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghDdXN0b21lchiSAQwLEgREZWFsGJUBDA' # dateTime = enc.decrypt_key(decoded['in']['dateTime']) #create report Entity report = levr.ReportedDeal(uid=db.Key(uid), dealID=db.Key(dealID)).put() #get human readable info for email deal = levr.Deal.get(dealID) business = db.get(deal.businessID) business_name = business.business_name deal_text = deal.deal_text user = levr.Customer.get(uid) alias = user.display_name logging.debug(report) #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 += 'reporter uid: ' + str(uid) + "\n\n" body += 'reporter display_name: ' + str(alias) + "\n\n" body += 'Business name: ' + str(business_name) + "\n\n" body += 'Business vicinity: ' + str(business.vicinity) + "\n\n" body += "Deal: " + str(deal_text) + "\n\n" body += "dealID: " + str(dealID) + "\n\n" message.body = body logging.debug(message.body) message.send() notifications = user.get_notifications() toEcho = {"success": True, "notifications": notifications} elif action == 'ninjaHasShared': logging.info(action) uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) keys = [dealID, uid] logging.debug(keys) #pull deal and user entities = db.get(keys) deal = entities[0] user = entities[1] logging.debug( levr_utils.log_model_props(deal, [ 'deal_text', 'business_name', 'gate_max', 'has_been_shared' ])) deal.share_deal() deal.put() logging.debug( levr_utils.log_model_props( deal, ['gate_max', 'has_been_shared'])) notifications = user.get_notifications() toEcho = {"success": True, "notifications": notifications} else: raise Exception('Unrecognized action')
def get(self): e = levr.Customer.all().filter('email','*****@*****.**').get() ethan = enc.encrypt_key(e.key()) p = levr.Customer.all().filter('email','*****@*****.**').get() pat = enc.encrypt_key(p.key()) a = levr.Customer.all().filter('email','*****@*****.**').get() alonso = enc.encrypt_key(a.key()) n = levr.Customer.all().filter('email','*****@*****.**').get() ninja = enc.encrypt_key(n.key()) url = '\'http://0.0.0.0:8080/api' ethan_url = url+'/user/'+ethan+'\' | python -mjson.tool' pat_url = url+'/user/'+pat+'\' | python -mjson.tool' alonso_url = url+'/user/'+alonso+'\' | python -mjson.tool' ninja_url = url+'/user/'+ninja+'\' | python -mjson.tool' levr_token = db.get(enc.decrypt_key(ethan)).levr_token self.response.out.headers['Content-Type'] = 'text/plain' self.response.out.write('LEVR TOKEN:\n\n') self.response.out.write(levr_token) self.response.out.write('\n\n\nFor ethan:\n\n') self.response.out.write(ethan) self.response.out.write('\n\n') self.response.out.write('curl '+ethan_url) self.response.out.write('\n\n\nFor pat:\n\n') self.response.out.write(pat) self.response.out.write('\n\n') self.response.out.write('curl '+pat_url) self.response.out.write('\n\n\n<b>For alonso: </b>\n\n') self.response.out.write(alonso) self.response.out.write('\n\n') self.response.out.write('curl '+alonso_url) self.response.out.write('\n\n\n<b>For ninja: </b>\n\n') self.response.out.write(ninja) self.response.out.write('\n\n') self.response.out.write('curl '+ninja_url) d = levr.Deal.all().ancestor(db.Key(enc.decrypt_key(ethan))).get() if d: deal = enc.encrypt_key(d.key()) deal_url = url+'/deal/'+deal+'\' | python -mjson.tool' self.response.out.write('\n\n\n<b>For deal stuff: </b>\n\n') self.response.out.write(deal) self.response.out.write('\n\n') # self.response.out.write('\n\n') self.response.out.write('curl '+deal_url) # projection = None projection = [ 'alias', 'new_notifications', 'first_name', 'last_name', 'karma', 'level', 'display_name', 'followers', 'foursquare_id', 'foursquare_token', 'foursquare_connected', 'foursquare_friends', 'twitter_id', 'twitter_token', 'twitter_token_secret', 'twitter_screen_name', 'twitter_connected', 'twitter_friends_by_sn', 'twitter_friends_by_id', 'facebook_connected', 'facebook_token', 'facebook_id', 'facebook_friends', 'email_friends', 'favorites', 'upvotes', 'downvotes', ] deal_projection = [ 'upvotes', 'downvotes', 'karma', 'geo_point', 'geo_hash' ] self.response.out.write('\n\n\n Ethan') self.response.out.write(levr.log_model_props(e,projection)) self.response.out.write('\n PAT') self.response.out.write(levr.log_model_props(p,projection)) self.response.out.write('\n ALONSO') self.response.out.write(levr.log_model_props(a,projection)) self.response.out.write('\nDEAL') if d: self.response.out.write(levr.log_model_props(d,deal_projection)) self.response.out.write('\n\n') notifications = levr.Notification.all().fetch(None) for n in notifications: self.response.out.write(levr.log_model_props(n))
def phoneFormat(deal,use,primary_cat=None): #dealID is used in a number of places dealID = enc.encrypt_key(str(deal.key())) # logging.info(deal.key()) # logging.info(dealID) #dealText dealText = deal.deal_text #dealTextExtra if deal.deal_type == 'bundle': logging.debug('flag bundle') dealTextExtra = '(with purchase of ' + deal.secondary_name + ')' else: logging.debug('flag single') dealTextExtra = '' if use == 'list' or use == 'myDeals' or use == 'widget': #list is search results #mydeals is for the list of a users uploaded deals #widget is for the html iframe for merchants data = {"dealID" : dealID, "imgURL" : 'http://beta.levr-production.appspot.com/phone/img?dealID='+dealID+'&size=list', "imgURLlarge" : 'http://beta.levr-production.appspot.com/phone/img?dealID='+dealID+'&size=dealDetail', "geoPoint" : deal.geo_point, "vicinity" : deal.vicinity, "dealText" : dealText, "dealTextExtra" : dealTextExtra, "description" : deal.description, "businessName" : deal.business_name, "primaryCat" : primary_cat, "isExclusive" : deal.is_exclusive} if use == 'myDeals': #shows list deal information AND statistics deal_parent = db.get(deal.key().parent()) logging.debug(deal_parent) data.update({ "gateRequirement" : deal.gate_requirement, #The number of redemptions needed to earn a dollar on this deal "gatePaymentPer" : deal.gate_payment_per, #The dollar amount we pay for each gate "earnedTotal" : deal.earned_total, #The amount of money that this deal has earned so far "paymentMax" : deal.gate_max*deal.gate_payment_per, #The most money we will pay them for this deal "paidOut" : deal.paid_out, #The amount of money that this deal has earned to date "dealStatus" : deal.deal_status, #active,pending,rejected,expired "dateEnd" : deal.date_end.__str__()[:10], #The date this deal becomes inactive "moneyAvailable" : deal_parent.money_available, #The amount of money that the NINJA has available for redemption "ninjaMoneyEarned" : deal_parent.money_paid, #The amount of money that the ninja has earned to date "weightedRedeems" : deal.count_redeemed % deal.gate_requirement, #The number of redemptions they need to earn another dollar "dealCountRedeemed" : deal.count_redeemed, #The number of times that the deal has been redeemed "shareURL" : levr_utils.create_share_url(deal) #The URL for them to share }) if use == 'widget': data.update({ "description" : deal.description, }) elif use == 'deal': #view deal information screen #grab business # logging.info(deal.businessID) # b = db.get(deal.businessID) #uploaded by a user data = {"dealID" : dealID, "imgURL" : 'http://beta.levr-production.appspot.com/phone/img?dealID='+dealID+'&size=dealDetail', "dealText" : dealText, "dealTextExtra" : dealTextExtra, "businessName" : deal.business_name, "vicinity" : deal.vicinity, "description" : deal.description, "isExclusive" : deal.is_exclusive} elif use == 'dealsScreen': deal_parent = db.get(deal.key().parent()) logging.debug(deal_parent.kind()) if deal_parent.kind() == 'Customer': #deal has a ninja parent. ninja = deal_parent alias = ninja.alias logging.debug(ninja) else: # business = deal_parent alias = '' data = {"barcodeURL" : 'http://beta.levr-production.appspot.com/phone/img?dealID='+dealID+'&size=dealDetail', "ninjaName" : alias, "isExclusive" : deal.is_exclusive} elif use == 'manage': data = { "dealID" :dealID, "dealText" :dealText, "dealTextExtra" :dealTextExtra, "secondaryName" :deal.secondary_name, "businessName" :deal.business_name, "vicinity" :deal.vicinity, "description" :deal.description, "isExclusive" :deal.is_exclusive, "imgURLLarge" :'http://beta.levr-production.appspot.com/phone/img?dealID='+dealID+'&size=dealDetail', "imgURLSmall" :'http://beta.levr-production.appspot.com/phone/img?dealID='+dealID+'&size=list', } data.update({'geoPoint':str(deal.geo_point)}) logging.info(levr_utils.log_dict(data)) return data
def post(self): #decode the input JSON and pull out the action parameter try: decoded = json.loads(self.request.body) action = decoded["action"] logging.info(action) try: uid = enc.decrypt_key(decoded["in"]["uid"]) user = levr.Customer.get(uid) logging.debug(levr_utils.log_model_props(user,['alias','email'])) except Exception, e: # logging.debug(uid) logging.debug(e) #switch action #***************signup************************************************ if action == "signup": logging.info('signup') #grab email/password from request body email = decoded["in"]["email"] alias = decoded["in"]["alias"] pw = decoded["in"]["pw"] toEcho = levr_utils.signupCustomer(email,alias,pw) #***************login************************************************* elif action == "login": logging.info('login') #grab email/password from request body email_or_owner = decoded["in"]["email_or_owner"] pw = decoded["in"]["pw"] toEcho = levr_utils.loginCustomer(email_or_owner,pw) #***************dealResults************************************************ elif action == "popularItems": logging.info('popularItems') lat = decoded['in']['latitude'] lon = decoded['in']['longitude'] request_point = levr.geo_converter(str(lat)+","+str(lon)) #get all deals in the area deals = levr_utils.get_deals_in_area(['all'],request_point) #compile a list of all of the tags tags = [] for deal in deals: tags.extend(list(set(deal.tags))) tags.sort() logging.debug(tags) #convert list of all tags to a dict of key=tag, val=frequency count = {} for tag in tags: # logging.debug(tag in count) if tag in count: count[tag] += 1 else: count[tag] = 1 #DEBUG #convert dict of tag:freq into list of tuples tuple_list1 = [] for key in count: tuple_list1.append((count[key],key)) tuple_list1.sort() tuple_list1.reverse() logging.debug(tuple_list1) #/DEBUG #remove unwanted stuff new_count = {} for tag in count: #search occurs more than once if count[tag] >1: #tag is not a number if tag.isdigit() == False: #tag is not in blacklist if tag not in blacklist: new_count[tag] = count[tag] # logging.debug(levr_utils.log_dict(count)) #convert dict of tag:freq into list of tuples tuple_list = [] for key in new_count: tuple_list.append((new_count[key],key)) tuple_list.sort() tuple_list.reverse() logging.debug(tuple_list) # for i in tuple_list: # logging.debug(i) #select only the most popular ones, and convert to list word_list = [x[1] for x in tuple_list] #if the popular items list is longer than 6, send entire list, else only send 6 logging.debug(word_list.__len__()) if word_list.__len__()<6: popularItems = word_list else: popularItems = word_list[:6] data = { 'popularItems' : popularItems } toEcho = {'success': True,'data':data} elif action == "dealResults": logging.info('dealResults') logging.info(decoded['in']) #grab primaryCat from the request body primaryCat = decoded["in"]["primaryCat"] #search term # start = decoded["in"]["start"] #starting index of search results #!!!not used numResults = decoded["in"]["size"] geo_point = decoded["in"]["geoPoint"] try: precision = int(decoded['in']['precision']) except: precision = 5 logging.debug(numResults) #length of search results list #should be None if we want all results #normalize search query primaryCat = primaryCat.lower() ###filter by location - get neighborhoods request_point = levr.geo_converter(geo_point) #normalize search query primaryCat = primaryCat.lower() #otherwise, search based on the tags tags = levr.tagger(primaryCat) logging.debug(tags) #batch get results. here is where we would set the number of results we want and the offset results = levr_utils.get_deals_in_area(tags,request_point,precision) #define an empty "dealResults" LIST, and initialize the counter to 0 #initialize isEmpty to 1 isEmpty = True dealResults = [] #iterate over the results #Want to grab deal information for each category for result in results: # logging.info('Rank: ' + str(result.rank)) #break if results limit is hit isEmpty = False #trade an object for a phone-formatted dictionary deal = levr.phoneFormat(result,'list',primaryCat) #indicate that this is not a sentinel deal['isSentinel'] = False logging.debug(result.geo_hash) #push the whole dictionary onto a list dealResults.append(deal) #increment the counter # resultsPushed += 1 logging.debug(dealResults.__len__()) ##debug # deals = levr.Deal.all().fetch(None) # for d in deals: # logging.debug(d.geo_hash) # ############OLD # #normalize search query # primaryCat = primaryCat.lower() # # # #build search query # q = levr.Deal.all() # # logging.debug("total number of deals: "+str(q.count())) # #only active deals # q.filter('deal_status','active') # #primaryCat will be mapresults to return everything # if primaryCat == 'all': # #get all deals - no filter # logging.debug('all') # else: # logging.debug('not all') # #normalize search query # primaryCat = primaryCat.lower() # #otherwise, search based on the tags # tags = levr.tagger(primaryCat) # logging.debug(tags) # #grab all deals where primary_cat is in tags # for tag in tags: # logging.debug('tag: '+str(tag)) # q.filter('tags =',tag) # # ###filter by location # request_point = levr.geo_converter(geo_point) # request_point = levr.geo_converter('42.35,-71.110') # center_hash = geohash.encode(request_point.lat,request_point.lon,precision=6) # hash_set = geohash.expand(center_hash) # # #get keys of all corresponding deals # deal_keys = [] # for query_hash in hash_set: # q.filter('geo_hash >=',query_hash) #min bound # q.filter('geo_hash <=',query_hash+"{") #max bound # deal_keys.extend(q.fetch(None)) # # #batch get results. here is where we would set the number of results we want and the offset # results = levr.Deal.get(deal_keys) # logging.debug # #define an empty "dealResults" LIST, and initialize the counter to 0 # #initialize isEmpty to 1 # isEmpty = True # #iterate over the results # #Want to grab deal information for each category # for result in results: ## logging.info('Rank: ' + str(result.rank)) # #break if results limit is hit # isEmpty = False # #trade an object for a phone-formatted dictionary # deal = levr.phoneFormat(result,'list',primaryCat) # #indicate that this is not a sentinel # deal['isSentinel'] = False # #push the whole dictionary onto a list # dealResults.append(deal) # #increment the counter ## resultsPushed += 1 # ###########################/OLD # #if isempty is true, send back suggested searches instead # if isEmpty == False: # dealResults.append({"isSentinel":True}) # # #go get (all) suggested searches # q = levr.EmptySetResponse.all() # #sory by index # q.order('index') # #loop through and append to data # for result in q: # searchObj = {"isSentinel":False, # "primaryCat":result.primary_cat, # "imgURL": levr_utils.URL+"/phone/img?size=emptySet&dealID=" + enc.encrypt_key(result.key()) # } # #push to stack # dealResults.append(searchObj) #get notifications # ninja = levr.Customer.get(uid) # notifications = ninja.get_notifications() #add boundary lon = [-71.13128751569184, -71.13747576487495, -71.13221920314751, -71.1315606660475, -71.1309193072284, -71.1297731686955, -71.12886527141396, -71.12773981063141, -71.12726203628873, -71.1216289071829, -71.12121164180434, -71.10497418088163, -71.1040140000405, -71.10267756839711, -71.0946922485677, -71.09243243954906, -71.09227823963506, -71.0950832349529, -71.097815779737, -71.11251814985596, -71.11356954283684, -71.11706884229781, -71.11779512636194, -71.11965434764042, -71.12212678446998, -71.12626327632834, -71.13026582412857] lat = [42.35604793867138, 42.3536306062291, 42.35301975662632, 42.35130590336475, 42.35025979303107, 42.34889896173047, 42.3474035881804, 42.34587017442897, 42.3454410032402, 42.34240376898205, 42.34200386027403, 42.34665152547006, 42.34437686280481, 42.34335156373593, 42.34544719585433, 42.34689842049458, 42.35112647889721, 42.35062769794382, 42.35071497934108, 42.35189268933054, 42.35225746246078, 42.35405913476999, 42.35424633071435, 42.35461863217454, 42.35493709975472, 42.35550741935002, 42.35597048179658] boundary = {"lat":lat, "lon":lon} if primaryCat == 'all': #echo back data - include boundary toEcho = {"success":True,"data":dealResults,"isEmpty":isEmpty,"boundary":boundary}#,"notifications":notifications} else: toEcho = {"success":True,"data":dealResults,"isEmpty":isEmpty}#,"notifications":notifications} #***************getUserFavs************************************************ elif action == "getUserFavs": ''' Grabs all of the favorites of a user - only data to show on list input : uid output: name, description, dealValue, dealType, imgPath, businessName, primaryCat ''' logging.info('getUserFavs') #grab inputs uid = enc.decrypt_key(decoded["in"]["uid"]) logging.debug(uid) logging.debug(decoded["in"]["uid"]) #grab user entity user = levr.Customer.get(uid) #grab list of favorties - list of deal keys favorites = user.favorites logging.debug(favorites) #batch grab favorited deals deals = levr.Deal.get(favorites) logging.debug(deals) #format deals for output to phone formatted_deals = [] for deal in deals: try: formatted_deals.append(levr.phoneFormat(deal,'list')) except: logging.warning('deal exists in favorites but was removed from the db') logging.warning(deal) # formatted_deals = [levr.phoneFormat(deal,'list') for deal in deals] #assign formatted deals to data list that doesnt follow standards data = formatted_deals #get notifications notifications = user.get_notifications() #output toEcho = {"success":True,"data":data,'notifications':notifications} #ADD FAVORITE*********************************************************** elif action == "addFav": ''' User pressed add favorite button = add favorite mapping input: dealID,uid,primaryCat output: success = bool ''' logging.info('addFav') #get inputs uid = enc.decrypt_key(decoded["in"]["uid"]) dealID = enc.decrypt_key(decoded["in"]["dealID"]) #get user entity user = levr.Customer.get(uid) #append dealID to favorites property user.favorites.append(db.Key(dealID)) logging.debug(user.favorites) # #get notifications notifications = user.get_notifications() #close entity user.put() #output toEcho = {"success":True,"notifications":notifications} #DELETE FAVORITE******************************************************** elif action == "delFav": ''' User presses delete favorite button - delete favorite mapping input: dealID,uid,primaryCat output: success = bool ''' logging.info('delFav') #get inputs uid = enc.decrypt_key(decoded["in"]["uid"]) dealID = enc.decrypt_key(decoded["in"]["dealID"]) deal_to_delete = db.Key(dealID) logging.debug(deal_to_delete) #get user entity user = levr.Customer.get(uid) logging.debug(levr_utils.log_model_props(user)) #grab favorites list favorites = user.favorites logging.debug(favorites) #generate new favorites list without requested dealID new_favorites = [deal for deal in favorites if deal != deal_to_delete] logging.debug(new_favorites) #reassign user favorites to new list user.favorites = new_favorites logging.debug(user.favorites) #get notifications notifications = user.get_notifications() #close entity user.put() toEcho = {"success":True,"notificaions":notifications} #***************getOneDeal************************************************ elif action == "getOneDeal": ''' Information to show on the deal information screen. input : primaryCat,dealID output : json object of all information necessary to describe deal ''' logging.info('getOneDeal') #grab input dealID dealID = enc.decrypt_key(decoded["in"]["dealID"]) primary_cat = decoded["in"]["primaryCat"] #fetch deal result = levr.Deal.get(dealID) #convert fetched deal into dictionary deal = levr.phoneFormat(result,'deal') #push the primary onto the dictionary deal.update({"primaryCat":primary_cat}) #echo back success! # #get notifications # ninja = levr.Customer.get(uid) # notifications = ninja.get_notifications() toEcho = {"success":True,"data":deal}#,"notificaions":notifications} elif action == "getMyDeals": ''' returns all of the deals that were uploaded by the ninja input : uid output : list of deal objects ''' logging.info('getMyDeals') uid = enc.decrypt_key(decoded["in"]["uid"]) logging.debug("encrypted uid: "+str(decoded["in"]["uid"])) logging.debug("uid: "+str(uid)) #grab all deal children of the user deals = levr.CustomerDeal.gql("WHERE ANCESTOR IS :1 ORDER BY date_uploaded DESC",uid).fetch(None) logging.debug(deals) #format CUSTOMER deals data = [levr.phoneFormat(x,'myDeals') for x in deals] #I believe this will just return data:None if deals is empty #flush their notifications ninja = levr.Customer.get(uid) # ninja.flush_new_redeem_count() # ninja.put() #get new notifications notifications = ninja.get_notifications() #Grab their cash out requests, if they exist cor_q = levr.CashOutRequest.gql("WHERE ANCESTOR IS :1 AND status=:2",uid,'pending') cor = cor_q.get() if cor != None: notifications["isPendingCashOut"] = True else: notifications["isPendingCashOut"] = False notifications["pendingCashOutAmount"] = ninja.money_available toEcho = {"success":True,"data":data,"notifications":notifications} elif action == "getMyStats": ''' returns the user's statistics input : uid output : ''' logging.info('getMyStats') uid = enc.decrypt_key(decoded['in']['uid']) #get user information user = db.get(uid) #format user information data = user.get_stats() #get new notifications notifications = user.get_notifications() toEcho = {"success":True,"data":data,"notifications":notifications} elif action == "checkRedeem": logging.info('checkRedeem') #grab corresponding deal uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) #grab the customer customer = levr.Customer.get(uid) #new notifications? notifications = customer.get_notifications() #don't try and redeem the same deal twice. . . if str(dealID) in customer.redemptions: toEcho = {"success":False,"data":{"message":"You have already redeemed this deal."},"notifications":notifications} else: toEcho = {"success":True,"notifications":notifications} #!!!!!!!!REMOVE THIS WHEN CHECKING IS PUT BACK IN # toEcho = {"success":True,"notifications":notifications} elif action == "getRedeemScreen": logging.info('getRedeemScreen') #grab inputs dealID = enc.decrypt_key(decoded['in']['dealID']) #grab the deal deal = levr.Deal.get(dealID) #format the deal data = levr.phoneFormat(deal,'dealsScreen') #echo toEcho = {"success":True,"data":data} elif action == "redeem": logging.info('redeem') #grab corresponding deal uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) #grab the deal deal = levr.Deal.get(dealID) #grab the customer customer = levr.Customer.get(uid) #don't try and redeem the same deal twice. . . # if dealID in customer.redemptions: # raise Exception('Cannot redeem a deal more than once') #increment deal "redeemed" count by 1 deal.count_redeemed += 1 #add deal to "redeemed" for the customer customer.redemptions.append(dealID) ###get customer new_redemptions if they are a ninja notifications = customer.get_notifications() #update customer customer.put() #Is this a deal uploaded by a ninja? If so, do ninja things if type(deal) is levr.CustomerDeal: #update deal ninjaStats deal.gate_count = int(math.floor(deal.count_redeemed / deal.gate_requirement)) if deal.gate_count > deal.gate_max: #reset if over deal.gate_count = deal.gate_max #update deal.earned_total difference = deal.update_earned_total() #put deal deal.put() #get the ninja ninjaKey = deal.key().parent() ninja = levr.Customer.get(ninjaKey) #update the ninja's earned amount ninja.update_money_earned(difference) #update the ninja's available amount ninja.update_money_available(difference) #notify the ninja of new redemptions ninja.increment_new_redeem_count() #echo stats ninja.echo_stats() deal.echo_stats() #update ninja ninja.put() else: #deal is owned by a business - FOR THE FUTURE! logging.info('Business!') pass toEcho = {"success":True,"notifications":notifications} elif action == "cashOut": logging.info('cashOut') uid = enc.decrypt_key(decoded['in']['uid']) # uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiYAQw' #grab the ninja ninja = levr.Customer.get(uid) #delete any current cashOutRequests q = levr.CashOutRequest.gql('WHERE ANCESTOR IS :1 AND status=:2',ninja.key(),'pending').fetch(None) for result in q: result.delete() #create a new cashOut request cor = levr.CashOutRequest(parent=ninja) cor.amount = ninja.money_available cor.money_available_paytime = cor.amount #get notifications notifications = ninja.get_notifications() if cor.amount == 0: toEcho = {"success":False,"data":{"message":"You need to earn something before you can cash out!","notifications":notifications}} else: cor.status = 'pending' cor.date_created = datetime.now() cor.put() toEcho = {"success":True,"notifications":notifications} ## ====== SPOOF ACCEPTANCE FOR BETA TEST ====== ## logging.debug(levr_utils.log_model_props(ninja)) logging.debug(levr_utils.log_model_props(cor)) #get corID #get cor #get the larger amount if money available at paytime is different if cor.amount != cor.money_available_paytime: amount = cor.money_available_paytime cor.note = 'The money available at paytime was greater than when the COR was created, so the paytime balance was used.' else: amount = cor.amount #get payment email receiver_email = ninja.email #set cor to "paid" cor.status = "paid" cor.date_paid = datetime.now() cor.payKey = 'this is a pay key' cor.put() #for each deal, make paid_out == earned_total q = levr.CustomerDeal.gql('WHERE ANCESTOR IS :1',ninja.key()) for deal in q: deal.paid_out = deal.earned_total deal.put() #are number consistent? logging.debug(cor.amount) logging.debug(cor.money_available_paytime) if cor.amount != cor.money_available_paytime: #remember to encrypt the key if this is being used for anything #other than just error logging logging.error('PAY MISMATCH AT UID:' + ninja.key().__str__()) #send email here later #set ninja money_available back to 0 ninja.money_available = 0.0 #increment money_paid for the customer ninja.money_paid += amount #update ninja ninja.put() logging.info('Payment completed!') logging.debug(levr_utils.log_model_props(ninja)) logging.debug(levr_utils.log_model_props(cor)) #send email to the ninja confirming their cashout! message = mail.EmailMessage( sender ="LEVR <*****@*****.**>", subject ="Levr Cash Out", to =receiver_email) logging.debug(message) body = 'Hey Beta Tester,\n\n' body += "You submitted a request to be paid for uploading deals to the Levr platform.\n\n" body += "If this were real life, this email would be letting you know that you were about to be paid via paypal an amount of $"+str(amount)+". " body += "Unfortunately your reality is being simulated. " body += "\n\nThanks for helping us test.\nSincerely,\nThe Levr Team" # #alt body for when not in beta # message = mail.EmailMessage( # sender ="LEVR <*****@*****.**>", # subject ="Levr Cash Out", # to =receiver_email) # body = 'Hey '+ninja.alias+',\n\n' # body += "You have submitted a request to be paid for the deals that you've uploaded to Levr.\n\n" # body += "The amount you have requested is: $"+str(amount)+".\n\n" # body += "Your request is in the process of being reviewed. If accepted, we will send you an email with instructions to receive your payment via PayPal." # body += "\n\nSincerely,\nThe Levr Team" # message.body = body # logging.debug(body) # message.send() # elif action == "getTargetedBusinesses": #get businesses that have property targeted = True logging.info('getTargetedBusinesses') businesses = levr.Business.all().filter('targeted =',True).order('-business_name').fetch(None) data = { 'targetedBusinesses':[] } for business in businesses: data['targetedBusinesses'].append({ "businessName" : business.business_name, "geoPoint" : str(business.geo_point), "vicinity" : business.vicinity, "businessID" : enc.encrypt_key(business.key()) }) toEcho = {"success":True,"data":data} elif action == "fetchUploadURL": logging.info('fetchUploadURL') upload_url = blobstore.create_upload_url('/phone/uploadDeal') logging.debug(upload_url) toEcho = {"success":True, "data":{"url":upload_url}} elif action == "checkBounty": logging.info('fetchUploadURL') where = "College campuses in Boston, MA" what = "Offers on food, drink, clothing, and entertainment" toEcho = {"success":True,"data":{"where":where,"what":what}} elif action == "reportDeal": #user reports a deal logging.info('reportDeal') uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) # uid = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9ucg8LEghDdXN0b21lchiRAQw' # dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghCdXNpbmVzcxiTAQwLEgREZWFsGJQBDA' # dealID = 'ahNkZXZ-bGV2ci1wcm9kdWN0aW9uchoLEghDdXN0b21lchiSAQwLEgREZWFsGJUBDA' # dateTime = enc.decrypt_key(decoded['in']['dateTime']) #create report Entity report = levr.ReportedDeal( uid = db.Key(uid), dealID = db.Key(dealID) ).put() #get human readable info for email deal = levr.Deal.get(dealID) business_name = deal.business_name logging.debug(business_name) if deal.deal_type == "single": deal_text = deal.deal_text else: deal_text = deal.deal_text +" with purchase of "+deal.secondary_name user = levr.Customer.get(uid) alias = user.alias deal_class = str(deal.class_name()) if deal_class == 'CustomerDeal': deal_kind = "Ninja Deal" elif deal_class == 'Deal': deal_kind = "Business Deal" else: raise ValueError('deal class_name not recognized') logging.debug(report) #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 += 'reporter uid: ' +str(uid)+"\n\n" body += 'reporter alias: ' +str(alias)+"\n\n" body += 'Business name: '+str(business_name)+"\n\n" body += "Deal: "+str(deal_text)+"\n\n" body += "Deal Kind: "+deal_kind+"\n\n" body += "dealID: "+str(dealID)+"\n\n" message.body = body logging.debug(message.body) message.send() notifications = user.get_notifications() toEcho = {"success":True,"notifications":notifications} elif action == 'ninjaHasShared': logging.info(action) uid = enc.decrypt_key(decoded['in']['uid']) dealID = enc.decrypt_key(decoded['in']['dealID']) keys = [dealID,uid] logging.debug(keys) #pull deal and user entities = db.get(keys) deal = entities[0] user = entities[1] logging.debug(levr_utils.log_model_props(deal,['deal_text','business_name','gate_max','has_been_shared'])) deal.share_deal() deal.put() logging.debug(levr_utils.log_model_props(deal,['gate_max','has_been_shared'])) notifications = user.get_notifications() toEcho = {"success":True,"notifications":notifications} else: raise Exception('Unrecognized action')
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 post(self): logging.debug(self.get_uploads()) if self.get_uploads(): #will this work? upload = self.get_uploads()[0] logging.info(upload) blob_key= upload.key() img_key = blob_key upload_flag = True else: upload_flag = False raise KeyError('Image was not uploaded') uid = enc.decrypt_key(self.request.get('uid')) businessID = enc.decrypt_key(self.request.get('businessID')) deal_text = self.request.get('deal_text') description = self.request.get('description') contentID = self.request.get('contentID') logging.info(uid) logging.info(businessID) logging.info(deal_text) logging.info(description) business = levr.Business.get(businessID) user = levr.Customer.get(uid) params = { 'uid' : user, 'business_name' : business.business_name, 'geo_point' : business.geo_point, 'vicinity' : business.vicinity, 'types' : ','.join(map(str, business.types)), #phone sends in a comma separated string, types is stored as a list 'deal_description' : description, 'deal_line1' : deal_text, 'distance' : -1, #is -1 if unknown = double 'development' : False, 'img_key' : img_key } dealID = levr.dealCreate(params,'phone_new_business') #fire off a task to do the image rotation stuff task_params = { 'blob_key' : str(img_key) } taskqueue.add(url='/tasks/checkImageRotationTask',payload=json.dumps(task_params)) #track event via mixpanel (asynchronous) # try: # properties = { # 'time' : time.time(), # 'distinct_id' : enc.encrypt_key(user.key()), # 'mp_name_tag' : user.display_name # } # mp_track.track('Deal uploaded','ab1137787f393161bd481e2756b77850',properties) # # to_increment = { # "Deals uploaded" : 1 # } # # mp_track.increment(enc.encrypt_key(user.key()),'ab1137787f393161bd481e2756b77850',to_increment) # # except: # levr.log_error() logging.info('/mobile/upload/complete/?uid='+urllib.quote(enc.encrypt_key(uid))) self.redirect('/mobile/upload/complete/?uid='+urllib.quote(enc.encrypt_key(uid)))
def post(self): #get uploaded image upload = self.get_uploads()[0] # upload = self.request.get('img') # upload = blobstore.Blob(upload) blob_key= upload.key() img_key = blob_key logging.info(upload) # new customer # c = levr.Customer(key='agtkZXZ-Z2V0bGV2cnIOCxIIQ3VzdG9tZXIYEgw') c = levr.Customer() c.email = '*****@*****.**' c.payment_email = c.email c.pw = enc.encrypt_password('ethan') c.alias = 'alonso' c.favorites = [] c.put() #new ninja # ninja = levr.Customer(key='agtkZXZ-Z2V0bGV2cnIOCxIIQ3VzdG9tZXIYCww') ninja = levr.Customer() ninja.email = '*****@*****.**' ninja.payment_email = c.email ninja.pw = enc.encrypt_password('ethan') ninja.alias = 'ninja' ninja.favorites = [] ninja.put() b = levr.Business.all(keys_only=True).get() # params = { # 'uid' : enc.encrypt_key(c.key()), # 'business' : enc.encrypt_key(str(b)), # 'deal_description' : 'description!!!', # 'deal_line1' : 'DEAL LINE!', # 'img_key' : img_key # } params = { 'uid' : enc.encrypt_key(c.key()), 'business' : enc.encrypt_key(str(b)), 'business_name' : 'Alamos', 'geo_point' : '42.2,-71.2', 'vicinity' : '10 Buick St', 'types' : 'aaa,type_o_negative', 'deal_description' : 'description!!!', 'deal_line1' : 'DEAL LINE!', 'img_key' : img_key } (share_url,dealID) = levr_utils.dealCreate(params,'phone_existing_business') logging.debug(share_url) logging.debug(dealID) # #new business ## b = levr.Business(key='agtkZXZ-Z2V0bGV2cnIOCxIIQnVzaW5lc3MYBAw') # b = levr.Business() # b.email = '*****@*****.**' # b.pw = enc.encrypt_password('alonso') # b.business_name = 'Shaws' # b.vicinity = '260 Everett St East Boston, MA' # b.alias = 'Joe' # b.contact_phone = '603-603-6003' # b.geo_point = levr.geo_converter("15.23213,60.2342") # b.types = ['tag1','tag2'] # b.put() # #new deal # d = levr.Deal(parent=b) # d.img = upload.key() # d.businessID = str(b) # d.business_name = 'Shaws' # d.secondary_name = 'second name' # d.deal_text = '50% off booze' # d.deal_type = 'bundle' # d.description = 'describe me, hun.' # d.img_path = './img/bobs-discount-furniture.png' # d.city = 'Qatar' # d.deal_status = 'active' # d.vicinity = '7 Gardner Terrace, Allston, MA' # d.tags = ['alonso','pat','ethan'] # d.deal_status = 'pending' # d.rank = 5 # # #create the share ID - based on milliseconds since epoch # milliseconds = int(levr_utils.unix_time_millis(datetime.now())) # #make it smaller so we get ids with 5 chars, not 6 # shortened_milliseconds = milliseconds % 100000000 # unique_id = converter.dehydrate(shortened_milliseconds) # d.share_id = unique_id # d.put() # # #new customer deal # cd = levr.CustomerDeal(parent=ninja) # cd.businessID = str(b) # cd.img = upload.key() # cd.business_name = 'Shaws' # cd.deal_text = '40% of sijo' # cd.deal_type = 'single' # cd.description = 'describe me, hun.' # cd.rating = 50 # cd.count_end = 101 # cd.count_redeemed = 0 # cd.count_seen = 43 # cd.new_redeem_count = 0 # cd.deal_status = 'pending' # cd.geo_point = levr.geo_converter('-80.,70.') # cd.vicinity = '1234 Cherry Lane, Boston, MA 02134, USA' # cd.tags = ['alonso','pat','ethan'] # cd.rank = 10 # #create the share ID - based on milliseconds since epoch # milliseconds = int(levr_utils.unix_time_millis(datetime.now())) # #make it smaller so we get ids with 5 chars, not 6 # shortened_milliseconds = milliseconds % 100000000 # unique_id = converter.dehydrate(shortened_milliseconds) # cd.share_id = unique_id # # cd.put() self.response.headers['Content-Type'] = 'text/plain' # self.response.out.write('/phone/img?dealID='+enc.encrypt_key(str(c.key()))+"&size=dealDetail") self.response.out.write(' I think this means it was a success')
def post(self): #A business owner is signing up in the tour try: logging.debug(self.request.headers) logging.debug(self.request.body) logging.debug(self.request.params) owner = levr.BusinessOwner( #create owner with contact info, put and get key email =self.request.get('email'), pw =enc.encrypt_password(self.request.get('password')), validated =False ).put() logging.debug(owner) #get the business info from the form business_name = self.request.get('business_name') geo_point = levr.geo_converter(self.request.get('geo_point')) vicinity = self.request.get('vicinity') types = self.request.get_all('types[]') #parse business name to create an upload email logging.debug(business_name) name_str = levr.tagger(business_name) logging.debug(name_str) #create unique identifier for the business if name_str[0] == 'the' or name_str[0] == 'a' or name_str[0] == 'an': #dont like the word the in front logging.debug('flag the!') identifier = ''.join(name_str[1:3]) else: identifier = ''.join(name_str[:2]) upload_email = "u+"+identifier+"@levr.com" #check if that already exists num = levr.Business.all().filter('upload_email =',upload_email).count() logging.debug(num) if num != 0: #a business already exists with that upload email #increment the upload_email = "u+"+identifier+str(num)+"@levr.com" logging.debug(upload_email) #check if business exists in database business = levr.Business.all().filter('business_name =', business_name).filter('vicinity =',vicinity).get() logging.debug(business) if business: logging.debug(levr_utils.log_model_props(business)) logging.debug(owner) logging.debug(upload_email) logging.debug('flag business already exists') #have to delete business entity instead of update because gae wont update reference on owner entity if business.owner == None: #grab this business! business.owner = owner upload_email = upload_email #TODO targeted will be set to false in the future, removing signed businesses from the ninja pool # targeted = False else: # db.delete(business) logging.error('A business owner just signed up claiming a business that another person has claimed') else: logging.debug('flag business does not exist') #create business entity business = levr.Business( #create business owner =owner, business_name =business_name, vicinity =vicinity, geo_point =geo_point, types =types, upload_email =upload_email #TODO targeted will be set to false in the future, removing signed businesses from the ninja pool # targeted =False ) logging.debug(levr_utils.log_model_props(business)) business.put() #creates new session for the new business session = get_current_session() session['ownerID'] = enc.encrypt_key(owner) session['loggedIn'] = True session['validated']= False logging.debug(session) #send email to pat so that he will know that there is a new business. message = mail.EmailMessage( sender ="LEVR AUTOMATED <*****@*****.**>", subject ="New Merchant signup", to ="*****@*****.**") logging.debug(message) body = 'New merchant\n\n' body += 'Business: ' +str(business_name)+"\n\n" body += 'Business ID: '+str(business)+"\n\n" body += "Owner Email:"+str(self.request.get('email'))+"\n\n" message.body = body message.send() #forward to appropriate page if self.request.get('destination') == 'upload': self.redirect('/merchants/upload') elif self.request.get('destination') == 'create': self.redirect('/merchants/deal') except: levr.log_error(self.request.body)
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 post(self): logging.debug(self.get_uploads()) if self.get_uploads(): #will this work? upload = self.get_uploads()[0] logging.info(upload) blob_key = upload.key() img_key = blob_key upload_flag = True else: upload_flag = False raise KeyError('Image was not uploaded') uid = enc.decrypt_key(self.request.get('uid')) businessID = enc.decrypt_key(self.request.get('businessID')) deal_text = self.request.get('deal_text') description = self.request.get('description') contentID = self.request.get('contentID') logging.info(uid) logging.info(businessID) logging.info(deal_text) logging.info(description) business = levr.Business.get(businessID) user = levr.Customer.get(uid) params = { 'uid': user, 'business_name': business.business_name, 'geo_point': business.geo_point, 'vicinity': business.vicinity, 'types': ','.join( map(str, business.types) ), #phone sends in a comma separated string, types is stored as a list 'deal_description': description, 'deal_line1': deal_text, 'distance': -1, #is -1 if unknown = double 'development': False, 'img_key': img_key } dealID = levr.dealCreate(params, 'phone_new_business') #fire off a task to do the image rotation stuff task_params = {'blob_key': str(img_key)} taskqueue.add(url='/tasks/checkImageRotationTask', payload=json.dumps(task_params)) #track event via mixpanel (asynchronous) # try: # properties = { # 'time' : time.time(), # 'distinct_id' : enc.encrypt_key(user.key()), # 'mp_name_tag' : user.display_name # } # mp_track.track('Deal uploaded','ab1137787f393161bd481e2756b77850',properties) # # to_increment = { # "Deals uploaded" : 1 # } # # mp_track.increment(enc.encrypt_key(user.key()),'ab1137787f393161bd481e2756b77850',to_increment) # # except: # levr.log_error() logging.info('/mobile/upload/complete/?uid=' + urllib.quote(enc.encrypt_key(uid))) self.redirect('/mobile/upload/complete/?uid=' + urllib.quote(enc.encrypt_key(uid)))