Example #1
0
	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)
Example #2
0
	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)
Example #3
0
	def post(self):
		try:
			#A merchant is creating a NEW deal from the online form
			
			#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
			else:
				raise Exception('Image was not uploaded')
			
			params = {
					'uid'				:self.request.get('uid'),
					'business'			:self.request.get('business'),
					'deal_description'	:self.request.get('deal_description'),
					'deal_line1'		:self.request.get('deal_line1'),
					'deal_line2'		:self.request.get('deal_line2'),
					'img_key'			:img_key
					}
			levr_utils.dealCreate(params, 'merchant_create')
			self.redirect('/merchants/manage')
		except:
			levr.log_error(self.request.body)
Example #4
0
	def get(self,*args,**kwargs):
		try:
			logging.info('Reporting for dudty, Captain')
			#grabthe user from the input
			user = kwargs.get('actor')
			
			
			
			try:
				data = api_utils.SpoofUndeadNinjaActivity(user).run()
				logging.debug(levr.log_dict(data))
				#set last login
				user = data['user']
			except:
				levr.log_error()
				
			user.date_last_login = datetime.now()
#			logging.debug(user.date_last_login)
			user.put()
			response = {'user':api_utils.package_user(user,True)}
			api_utils.send_response(self,response,user)
			
			
		except:
			levr.log_error()
			api_utils.send_error(self,'Server Error')
Example #5
0
	def get(self,*args,**kwargs):
		'''
		Input: uid
		response: {}
		'''
		try:
			logging.debug('DELETE FAVORITE\n\n\n')
			logging.debug(kwargs)
			
			user 	= kwargs.get('actor')
			deal 	= kwargs.get('deal')
			
#			uid 	= user.key()
			dealID 	= deal.key()
			
			
			#if the deal is in the users favorites, remove it. else do nothing
			if dealID in user.favorites:
				user.favorites.remove(dealID)
			
			#replace entities
			db.put(user)
			
			
			response = {}
			
			api_utils.send_response(self,response,user)
		except:
			levr.log_error()
			api_utils.send_error(self,'Server Error')
Example #6
0
	def get(self,*args,**kwargs):
		'''
		Get information about a deal.
		
		Input: None
		Output:{
			meta:{
				success
				errorMsg
				}
			response:{
				<DEAL OBJECT>
				}
			}
		'''
		try:
			logging.debug('DEAL INFO\n\n\n')
			logging.debug(kwargs)
			deal	= kwargs.get('deal')
			private	= kwargs.get('private')
			
			assert deal, 'Deal could not be found'
			response = {
				'deal'	: api_utils.package_deal(deal,private)
			}
			api_utils.send_response(self,response)
		except AssertionError,e:
			levr.log_error(e)
			api_utils.send_error(self,e.message)
Example #7
0
    def get(self, *args, **kwargs):
        try:
            logging.info('fetchUploadURL\n\n\n')
            logging.debug(kwargs)
            user = kwargs.get('user')

            #create blobstore user
            upload_url = blobstore.create_upload_url('/api/upload/post')
            logging.debug(upload_url)

            if os.environ['SERVER_SOFTWARE'].startswith('Development') == True:
                #we are on the development environment
                URL = 'http://0.0.0.0:8080/'
            else:
                #we are deployed on the server
                URL = 'levr.com/'

            #create share url
            share_url = URL + levr.create_unique_id()

            response = {'uploadURL': upload_url, 'shareURL': share_url}
            api_utils.send_response(self, response, user)
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Example #8
0
    def get(self, *args, **kwargs):
        '''
		#PARTIALLY RESTRICTED
		inputs:
		Output:{
			meta:{
				success
				errorMsg
				}
			response:{
				<USER OBJECT>
				}
		'''
        try:
            logging.debug('USER INFO\n\n')
            user = kwargs.get('user')
            private = kwargs.get('private')
            #create response object
            response = {'user': api_utils.package_user(user, private)}

            #respond
            api_utils.send_response(self, response, user)
        except:
            levr.log_error(self.request)
            api_utils.send_error(self, 'Server Error')
Example #9
0
	def get(self):
		try:
			now = datetime.now()
			#fetch all deals that are set to expire
			deals = levr.Deal.all().filter('deal_status','active').filter('date_end <=',now).filter('date_end !=',None).fetch(None)
			logging.info('<-- With date_end -->\n\n')
			for deal in deals:
				logging.info(str(deal.date_end)+' --> '+ deal.deal_text+'\n')
				
			
			### DEBUG ###
			# This is the control group of all active deals
			logging.info('\n\n<-- Without date end -->\n\n')
			deals2 = levr.Deal.all().filter('deal_status','active').fetch(None)
			for deal in deals2:
				logging.info(str(deal.date_end)+' --> '+ deal.deal_text+ '\n')
			## /DEBUG ###
			
			
			#set deal_status to expired
			for deal in deals:
				# expire the deal
				deal.expire()
#				levr.remove_memcache_key_by_deal(deal)
#				#set expired deal status
#				deal.deal_status = 'expired'
#				#grab the deal owner
#				to_be_notified = deal.key().parent()
#				#create the notification
#				levr.create_notification('expired',to_be_notified,None,deal.key())
			#replace deals
			db.put(deals)
			
		except:
			levr.log_error()
Example #10
0
	def post(self):
		try:
			
			logging.info('''
				
				THE MERGE USERS TASK IS RUNNING
				
				''')
			
			payload = json.loads(self.request.body)
			
			uid = payload['uid']
			contentID = payload['contentID']
			service = payload['service']
			
			#grab the user
			user = levr.Customer.get(uid)
			#grab the donor's foursquare token
			floating_content = levr.FloatingContent.gql('WHERE contentID=:1',contentID).get()
			donor = floating_content.user
			
			api_utils.merge_customer_info_from_B_into_A(user,donor,service)
			
		except:
			levr.log_error()
Example #11
0
	def post(self):
		try:
			
			logging.info('''
				
				SKYNET IS TEXTING THE FOUNDERS
				
				''')
			
			payload = json.loads(self.request.body)
			logging.info(payload['user_string'])
			#twilio credentials
			sid = 'AC4880dbd1ff355288728be2c5f5f7406b'
			token = 'ea7cce49e3bb805b04d00f76253f9f2b'
			twiliourl='https://api.twilio.com/2010-04-01/Accounts/AC4880dbd1ff355288728be2c5f5f7406b/SMS/Messages.json'
			
			auth_header = 'Basic '+base64.b64encode(sid+':'+token)
			logging.info(auth_header)
			
			numbers = ['+16052610083','+16035605655','+16173124536','+16173124536','+12036329029']
			
			for number in numbers:
				request = {'From':'+16173608582',
							'To':number,
							'Body':'Awwwww yeeeaahhhhh. You have a new user: '******'user_string']}
			
				result = urlfetch.fetch(url=twiliourl,
									payload=urllib.urlencode(request),
									method=urlfetch.POST,
									headers={'Authorization':auth_header})
									
				logging.info(levr.log_dict(result.__dict__))
			
		except:
			levr.log_error()
Example #12
0
	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)
Example #13
0
	def get(self,*args,**kwargs):
		'''
		#PARTIALLY RESTRICTED
		inputs:
		Output:{
			meta:{
				success
				errorMsg
				}
			response:{
				<USER OBJECT>
				}
		'''
		try:
			logging.debug('USER INFO\n\n')
			user 	= kwargs.get('user')
			private	= kwargs.get('private')
			#create response object
			response = {
					'user'	: api_utils.package_user(user,private)
					}
			
			#respond
			api_utils.send_response(self,response,user)
		except:
			levr.log_error(self.request)
			api_utils.send_error(self,'Server Error')
Example #14
0
    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)
Example #15
0
	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()
Example #16
0
 def get(self):
     try:
         template = jinja_environment.get_template(
             'templates/merchantBeta.html')
         self.response.out.write(template.render())
     except:
         levr.log_error()
Example #17
0
	def post(self):
		try:
			logging.info('''
			
			THE FOURSQUARE DEAL UPDATE TASK IS RUNNING
			
			''')
			
			payload = json.loads(self.request.body)
			
			foursquare_id = payload['foursquare_id']
			deal_id = payload['deal_id']
			uid = payload['uid']
			token =  payload['token']
			deal_status = payload['deal_status']
			
			logging.info('This task was started by a user/deal with the following information:')
			logging.info('UID: '+uid)
			logging.info('Foursquare user token: '+token)
			logging.info('Reported deal ID: '+deal_id)	
			logging.info('Business foursquare ID: '+foursquare_id)
			logging.info('deal_status: '+deal_status)
			
			api_utils.update_foursquare_business(foursquare_id,deal_status,token)
			
			
		except:
			levr.log_error()
Example #18
0
	def post(self):
		try:
			#A merchant is EDITING a deal from the online form
			logging.debug(self.request.params)
			
			#make sure than an image is uploaded
			logging.debug(self.get_uploads())
			if self.get_uploads().__len__()>0: #will this work?
				#image has been uploaded
				upload_flag = True
				upload	= self.get_uploads()[0]
				blob_key= upload.key()
				img_key = blob_key
			else:
				#image has not been uploaded
				upload_flag = False
				img_key = ''
			logging.debug('upload_flag: '+str(upload_flag))
			params = {
					'uid'				:self.request.get('uid'),
					'business'			:self.request.get('business'),
					'deal'				:self.request.get('deal'),
					'deal_description'	:self.request.get('deal_description'),
					'deal_line1'		:self.request.get('deal_line1'),
					'deal_line2'		:self.request.get('deal_line2'),
					'img_key'			:img_key
					}
			
			levr_utils.dealCreate(params, 'merchant_edit',upload_flag)
			self.redirect('/merchants/manage')
		except:
			levr.log_error(self.request.body)
Example #19
0
    def get(self, *args, **kwargs):
        '''
		Input: uid
		response: {}
		'''
        try:
            logging.debug('DELETE FAVORITE\n\n\n')
            logging.debug(kwargs)

            user = kwargs.get('actor')
            deal = kwargs.get('deal')

            #			uid 	= user.key()
            dealID = deal.key()

            #if the deal is in the users favorites, remove it. else do nothing
            if dealID in user.favorites:
                user.favorites.remove(dealID)

            #replace entities
            db.put(user)

            response = {}

            api_utils.send_response(self, response, user)
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Example #20
0
	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
			
			template_values = {
				'owner'		: owner,
				'business'	: business,
				'mode'		: '', #which form to show
				'error'		: ''
				}
				
			template = jinja_environment.get_template('templates/editAccount.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Example #21
0
	def get(self):
		'''This is for the page where they see info about how to upload via email'''
		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)
			if not owner:
				self.redirect('/merchants')
			
			#get the business
			business = owner.businesses.get()#TODO: this will be multiple businesses later
			
			
			template_values = {
				'headerData':headerData,
				'title'		:'Upload Instructions',
				'owner'		:owner,
				'business'	:business
			}
			
			template = jinja_environment.get_template('templates/emailUpload.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Example #22
0
    def get(self, *args, **kwargs):
        try:
            logging.info("fetchUploadURL\n\n\n")
            logging.debug(kwargs)
            user = kwargs.get("user")

            # create blobstore user
            upload_url = blobstore.create_upload_url("/api/upload/post")
            logging.debug(upload_url)

            if os.environ["SERVER_SOFTWARE"].startswith("Development") == True:
                # we are on the development environment
                URL = "http://0.0.0.0:8080/"
            else:
                # we are deployed on the server
                URL = "levr.com/"

                # create share url
            share_url = URL + levr.create_unique_id()

            response = {"uploadURL": upload_url, "shareURL": share_url}
            api_utils.send_response(self, response, user)
        except:
            levr.log_error()
            api_utils.send_error(self, "Server Error")
Example #23
0
	def get(self,*args,**kwargs):
		'''Returns ONLY an image for a deal specified by uid
		Gets the image from the blobstoreReferenceProperty deal.img'''
		try:
			logging.info('IMAGE\n\n\n')
			user	= kwargs.get('user')
#			uid		= user.key()
			size	= kwargs.get('size')
			
			# fetch from relational db
			photo = user.img_ref.get()
			
			assert photo, 'Customer does not have an image in the database'
			# grab img key from blobstore
			blob_key = photo.img
			
			
			#send image to response output
			if not api_utils.send_img(self,blob_key,size):
				return
			
			#test
		except:
			levr.log_error()
			self.response.headers['Content-Type'] = 'image/jpeg'
			self.response.out.write(None)
Example #24
0
    def get(self, *args, **kwargs):
        '''
		Get information about a deal.
		
		Input: None
		Output:{
			meta:{
				success
				errorMsg
				}
			response:{
				<DEAL OBJECT>
				}
			}
		'''
        try:
            logging.debug('DEAL INFO\n\n\n')
            logging.debug(kwargs)
            deal = kwargs.get('deal')
            private = kwargs.get('private')

            assert deal, 'Deal could not be found'
            response = {'deal': api_utils.package_deal(deal, private)}
            api_utils.send_response(self, response)
        except AssertionError, e:
            levr.log_error(e)
            api_utils.send_error(self, e.message)
Example #25
0
    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)
Example #26
0
    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)
Example #27
0
	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 = "&lt;iframe src='"+levr_utils.URL+"/widget?id="+business.widget_id+"' frameborder='0' width='1000' height='400' &gt;Your Widget&lt;/iframe&gt; />"
		
#			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()
Example #28
0
    def get(self, *args, **kwargs):
        '''Returns ONLY an image for a deal specified by uid
		Gets the image from the blobstoreReferenceProperty deal.img'''
        try:
            logging.info('IMAGE\n\n\n')
            user = kwargs.get('user')
            #			uid		= user.key()
            size = kwargs.get('size')

            # fetch from relational db
            photo = user.img_ref.get()

            assert photo, 'Customer does not have an image in the database'
            # grab img key from blobstore
            blob_key = photo.img

            #send image to response output
            if not api_utils.send_img(self, blob_key, size):
                return

            #test
        except:
            levr.log_error()
            self.response.headers['Content-Type'] = 'image/jpeg'
            self.response.out.write(None)
Example #29
0
    def post(self):
        try:
            logging.info('''
			
			THE FOURSQUARE DEAL UPDATE TASK IS RUNNING
			
			''')

            payload = json.loads(self.request.body)

            foursquare_id = payload['foursquare_id']
            deal_id = payload['deal_id']
            uid = payload['uid']
            token = payload['token']
            deal_status = payload['deal_status']

            logging.info(
                'This task was started by a user/deal with the following information:'
            )
            logging.info('UID: ' + uid)
            logging.info('Foursquare user token: ' + token)
            logging.info('Reported deal ID: ' + deal_id)
            logging.info('Business foursquare ID: ' + foursquare_id)
            logging.info('deal_status: ' + deal_status)

            api_utils.update_foursquare_business(foursquare_id, deal_status,
                                                 token)

        except:
            levr.log_error()
Example #30
0
	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()
Example #31
0
    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()
Example #32
0
    def post(self):
        try:

            logging.info('''
				
				THE MERGE USERS TASK IS RUNNING
				
				''')

            payload = json.loads(self.request.body)

            uid = payload['uid']
            contentID = payload['contentID']
            service = payload['service']

            #grab the user
            user = levr.Customer.get(uid)
            #grab the donor's foursquare token
            floating_content = levr.FloatingContent.gql(
                'WHERE contentID=:1', contentID).get()
            donor = floating_content.user

            api_utils.merge_customer_info_from_B_into_A(user, donor, service)

        except:
            levr.log_error()
Example #33
0
	def post(self):
		try:
			#to deploy: change paypaladaptivepayment argument to False (takes out of sandbox)
			#remove email override
	
			#get corID
			corID = enc.decrypt_key(self.request.get('corID'))
			#get cor
			cor = levr.CashOutRequest.get(corID)
			#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 ninja
			ninja = levr.Customer.get(cor.key().parent())
			#get payment email
			receiver_email = ninja.payment_email
			receiver_email = "*****@*****.**"
			#Change to false and enter information in above class to deploy
			paypal_init = PaypalAdaptivePayment(True)
			response = paypal_init.initialize_payment(amount,receiver_email,"http://cancel_url.com","http://return_url.com")
			logging.info(response)
		
			if response['paymentExecStatus'] == 'COMPLETED':
				#set cor to "paid"
				cor.status = "paid"
				cor.date_paid = datetime.now()
				cor.payKey = response['payKey']
			
				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?
				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!')

			self.response.out.write(self.request.get(corID) + '<p>Payment status: <strong>' + response['paymentExecStatus'] + '</strong></p><p><a href="/payments/view">Next Request</a></p>')
		except:
			levr.log_error()
Example #34
0
	def get(self):
		try:
			logging.debug('!!!!!!')
			logging.info('asdasd')
			template = jinja_environment.get_template('templates/new.html')
			self.response.out.write(template.render())
		except:
			levr.log_error()
Example #35
0
    def get(self, *args, **kwargs):
        '''
		/user/uid/favorites
		
		Get all of a users favorite deals
		
		inputs: 
		
		response:{
			numResults: <int>
			deals: [<deal>,<deal>]
			}
		'''
        #RESTRICTED
        try:
            logging.info("\n\nGET USER FAVORITES")
            logging.info(kwargs)
            logging.info(args)

            user = kwargs.get('user')
            #			uid 	= user.key()
            private = kwargs.get('private')
            limit = kwargs.get('limit')
            offset = kwargs.get('offset')

            #grab all favorites
            favorites = user.favorites

            #check list is longer than offset
            if favorites.__len__() > offset:
                #grab list from offset to end
                favorites = favorites[offset:]
                #check list is longer than limit
                if favorites.__len__() > limit:
                    #there are more favorites than the limit requests so shorten favorites
                    favorites = favorites[:limit]

                #fetch all favorite entities
                favorites = levr.Deal.get(favorites)

                deals = []

                #package each deal object
                for deal in favorites:
                    if deal:
                        deals.append(api_utils.package_deal(deal, False))
            else:
                #favorites is either empty or the offset is past the length of it
                deals = []
            #create response object
            response = {'numResults': str(favorites.__len__()), 'deals': deals}
            logging.debug(response)
            #respond
            api_utils.send_response(self, response, user)

        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Example #36
0
    def get(self, *args, **kwargs):
        '''
		Input: uid
		'''
        try:
            logging.debug("REPORT\n\n\n")
            logging.debug(kwargs)

            user = kwargs.get('actor')
            deal = kwargs.get('deal')

            uid = user.key()
            dealID = deal.key()

            #create report Entity
            levr.ReportedDeal(uid=uid, dealID=dealID).put()

            #is it a foursquare deal that got reported?
            if deal.origin == 'foursquare':
                #get the business
                business = levr.Business.get(deal.businessID)
                #get the business' foursquare ID
                foursquare_id = business.foursquare_id
                #is the user a foursquare user?
                if user.foursquare_token > '':
                    token = user.foursquare_token
                else:
                    token = 'random'
                #fire off a task to review the foursquare deals for this business
                task_params = {
                    'foursquare_id': foursquare_id,
                    'token': token,
                    'deal_id': str(deal.key()),
                    'uid': str(user.key()),
                    'deal_status': deal.deal_status
                }
                taskqueue.add(url='/tasks/foursquareDealUpdateTask',
                              payload=json.dumps(task_params))

            #send notification via email
            message = mail.EmailMessage(
                sender="LEVR AUTOMATED <*****@*****.**>",
                subject="New Reported Deal",
                to="*****@*****.**")

            logging.debug(message)
            body = 'New Reported Deal\n\n'
            body += levr.log_model_props(user, ['email', 'display_name', ''])
            body += str(user.email) + ' is reporting ' + str(deal.deal_text)
            message.body = body
            logging.debug(message.body)
            message.send()

            api_utils.send_response(self, {}, user)
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Example #37
0
	def get(self):
		try:
			logging.debug(self.request)
			dealID = self.request.get('id')
			dealID = enc.decrypt_key(dealID)
			db.delete(dealID)
			
			self.redirect('/merchants/manage')
		except:
			levr.log_error()
Example #38
0
	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)
Example #39
0
    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()
Example #40
0
	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()
Example #41
0
	def get(self):
		try:
			now = datetime.now()+datetime.datetime.relativedelta(days=+20)
			expired = levr.CustomerDeal.gql("WHERE deal_status=:'active' AND date_end <:1",now)
			for x in expired:
				x.deal_status = "expired"
				x.push()
			
		except:
			levr.log_error()
		else:
			logging.info('Deals have been cleaned')
Example #42
0
    def get(self, *args, **kwargs):
        '''
		A user logs in with levr using an email or alias, and a password
		'''
        try:
            #RESTRICTED
            logging.debug('LOGIN LEVR\n\n\n')
            logging.debug(kwargs)

            email_or_owner = kwargs.get('email_or_owner')
            pw = kwargs.get('pw')
            pw = enc.encrypt_password(pw)

            #check both email and password

            r_email = levr.Customer.gql('WHERE email = :1 AND pw=:2',
                                        email_or_owner, pw).get()
            r_alias = levr.Customer.gql('WHERE alias = :1 AND pw=:2',
                                        email_or_owner, pw).get()
            if r_email:
                #match based on email
                existing_user = r_email
            elif r_alias:
                #match based on alias
                existing_user = r_alias
            else:
                api_utils.send_error(self, 'Authentication failed.')
                return

            #create or refresh the alias
            existing_user = levr.build_display_name(existing_user)

            #===================================================================
            # Spoof Ninja Activity!
            #===================================================================

            data = api_utils.SpoofUndeadNinjaActivity(existing_user).run()
            logging.debug(levr.log_dict(data))
            #set last login
            existing_user = data['user']
            #still here? update last login by putting
            existing_user.put()

            #package user, private setting, send token
            response = {
                'user':
                api_utils.package_user(existing_user, True, send_token=True)
            }

            api_utils.send_response(self, response, existing_user)
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Example #43
0
	def get(self):
		try:
			logging.debug('\n\n\t\t Hit the Authorize Begin Handler \n\n')
			client_id		= facebook_auth['client_id']
			state			= uuid.uuid4()
			scope			= 'publish_actions'
			redirect_uri	= 'http://levr-production.appspot.com/facebook/authorize/complete'
			url = 'https://www.facebook.com/dialog/oauth?client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}&state={scope}'.format(
														client_id = client_id, redirect_uri= redirect_uri, scope= scope, state= state)
			logging.debug(url)
			self.redirect(url)
		except Exception,e:
			levr.log_error(e)
Example #44
0
	def get(self,*args,**kwargs): #@UnusedVariable
		try:
			self.response.headers['Content-Type'] = 'text/plain'
			
			deal = kwargs.get('deal')
			deal.been_reviewed = True
			deal.put()
			
			self.response.out.write('Yeah. What it do?')
			self.response.out.write(levr.log_model_props(deal, ['deal_text','deal_status','been_reviewed']))
		except Exception,e:
			levr.log_error(e)
			self.response.out.write('Error approving: '+str(e))
Example #45
0
	def post(self):
		try:
			dealID = enc.decrypt_key(self.request.get('deal'))
			logging.debug(dealID)
			deal = levr.CustomerDeal.get(dealID)
			deal.deal_status = 'rejected'
			deal.been_reviewed = True
			deal.reject_message = self.request.get('reject_message')
			deal.put()
			self.redirect('/admin/pending')
		except:
			levr.log_error()
			self.response.out.write('Error rejecting. See logs.')
Example #46
0
	def get(self):
		try:
#			dealID		= enc.decrypt_key(self.request.get('deal'))
			businessID	= self.request.get('id') #do not decrypt
#			session		= get_current_session()
#			customer_key= enc.decrypt_key(session['uid'])
#			customer	= levr.Customer.get(customer_key)
#			fav			= levr.Favorite(parent=customer.key())
#			fav.dealID	= dealID
#			fav.put()
			self.redirect('/widget/remote?id='+businessID+'action=success')
		except:
			levr.log_error()
			self.redirect('/widget/remote?id='+businessID+'&success=False')
Example #47
0
    def get(self, *args, **kwargs):  #@UnusedVariable
        try:
            self.response.headers['Content-Type'] = 'text/plain'

            deal = kwargs.get('deal')
            deal.been_reviewed = True
            deal.put()

            self.response.out.write('Yeah. What it do?')
            self.response.out.write(
                levr.log_model_props(
                    deal, ['deal_text', 'deal_status', 'been_reviewed']))
        except Exception, e:
            levr.log_error(e)
            self.response.out.write('Error approving: ' + str(e))
Example #48
0
    def post(self, *args, **kwargs):
        try:
            #RESTRICTED
            logging.debug('CONNECT FOURSQUARE\n\n\n')
            logging.debug(kwargs)

            user = kwargs.get('actor')
            foursquare_token = kwargs.get('remoteToken')
            new_user_details = None
            new_friends = None
            #===================================================================
            # Check to see if there are multiple accounts
            # i.e. the user that is connecting w/ foursquare has an existing fs account with levr
            #===================================================================
            # check for an existing foursquare user
            foursquare_user = levr.Customer.all().filter(
                'foursquare_token', foursquare_token).get()
            # If a user was found in the db with the requested foursquare credentials,
            # and that user is not the same user as the one requesting the connection,
            # merge the foursquare created account into the requesting user (i.e. the levr account user)
            if foursquare_user and foursquare_user is not user:
                #this means the user has multiple accounts that need to be merged
                data = api_utils.merge_customer_info_from_B_into_A(
                    user, foursquare_user, 'foursquare')
                user = data[0]
            # Otherwise, act normally. Simply connect. If the user already has foursquare credentials,
            # this will refresh their foursquare information
            else:
                #create an instance of the Foursquare social connection class
                user = social.Foursquare(user, 'verbose')

                try:
                    user, new_user_details, new_friends = user.first_time_connect(
                        foursquare_token=foursquare_token)
                except Exception, e:
                    levr.log_error()
                    assert False, 'Could not connect with foursquare. '.format(
                        '')

            response = {
                'user': api_utils.package_user(user, True)
                #					'new_friends'		: [enc.encrypt_key(f) for f in new_friends],
                #					'new_user_details'	: new_user_details
            }
            if new_user_details:
                response['new_user_details'] = new_user_details
            if new_friends: response['new_friends'] = new_friends
            api_utils.send_response(self, response, user)
Example #49
0
    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)
Example #50
0
 def get(self):
     try:
         logging.debug('\n\n\t\t Hit the Authorize Begin Handler \n\n')
         client_id = facebook_auth['client_id']
         state = uuid.uuid4()
         scope = 'publish_actions'
         redirect_uri = 'http://levr-production.appspot.com/facebook/authorize/complete'
         url = 'https://www.facebook.com/dialog/oauth?client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}&state={scope}'.format(
             client_id=client_id,
             redirect_uri=redirect_uri,
             scope=scope,
             state=state)
         logging.debug(url)
         self.redirect(url)
     except Exception, e:
         levr.log_error(e)
Example #51
0
	def get(self):
		try:
			'''template html page for entering lost password info'''
			#email will be false if an invalid email was passed, otherwise will be true
			try:
				success = self.request.get('success')
			except:
				success = 'True'
		
			template_values = {"success":success}
		
			jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
			template = jinja_environment.get_template('templates/lostPassword.html')
			self.response.out.write(template.render(template_values))
		except:
			levr.log_error()
Example #52
0
class ConfirmPromotionHandler(api_utils.PromoteDeal):
    @api_utils.validate(None,
                        'param',
                        user=True,
                        levrToken=True,
                        promotionID=True,
                        deal=True,
                        receipt=True)
    @api_utils.private
    def post(self, *args, **kwargs):  #@UnusedVariable
        '''
		A handler to confirm that payment was received for a promotion
		'''
        user = kwargs.get('actor')
        deal = kwargs.get('deal')
        promotion_id = kwargs.get('promotionID')
        receipt = kwargs.get('receipt')

        try:
            # init the super class
            super(ConfirmPromotionHandler, self).__initialize__(deal, user)
            # confirm the promotion
            self.confirm_promotion(promotion_id, receipt)
            # return success - send all deals
            response = self.get_all_deals_response()
            self.send_response(response, self.user)

        except AssertionError, e:
            self.send_error(e)
            logging.warning(e)
        except Exception, e:
            levr.log_error(e)
            self.send_error()
Example #53
0
    def post(self):
        try:
            logging.debug(self.request.body)
            payload = json.loads(self.request.body)
            deal_keys = payload['deal_keys']
            deals = db.get(deal_keys)
            for deal in deals:
                try:
                    deal.increment_views()
                except:
                    levr.log_error()


#				logging.debug(deal.views)
        except Exception, e:
            levr.log_error(e)
Example #54
0
class CancelPromotionHandler(api_utils.PromoteDeal):
    @api_utils.validate(
        None,
        'param',
        user=True,
        levrToken=True,
        promotionID=True,
        deal=True,
    )
    @api_utils.private
    def post(self, *args, **kwargs):  #@UnusedVariable
        user = kwargs.get('actor')
        promotion_id = kwargs.get('promotionID')
        deal = kwargs.get('deal')
        #		development = kwargs.get('development')
        try:
            # init super class
            super(CancelPromotionHandler, self).__initialize__(deal, user)

            # remove the promotion
            if promotion_id == 'all':
                for p in self.deal.promotions:
                    self.remove_promotion(p)
            else:
                self.remove_promotion(promotion_id)
            # send success
            response = self.get_all_deals_response()
            self.send_response(response, self.user)
        except AssertionError, e:
            self.send_error(e)
            logging.warning(e)
        except Exception, e:
            levr.log_error(e)
            self.send_error()
Example #55
0
class RejectHandler(api_utils.BaseClass):
    @api_utils.validate('deal', None)
    def get(self, *args, **kwargs):  #@UnusedVariable
        try:
            self.response.headers['Content-Type'] = 'text/plain'
            deal = kwargs.get('deal')
            assert deal.been_reviewed == False, 'Deal has already been reviewed.'
            # remove the deal from the memcache
            try:
                levr.remove_memcache_key_by_deal(deal)
            except:
                levr.log_error('Could not remove key from memcache')
            deal.deal_status = 'rejected'
            deal.been_reviewed = True
            deal.put()

            self.response.out.write(
                'And the Lord said unto his children, "It has been done."\n\n')
            self.response.out.write(
                levr.log_model_props(
                    deal, ['deal_text', 'deal_status', 'been_reviewed']))
        except AssertionError, e:
            self.response.out.write(e)
        except Exception, e:
            levr.log_error(e)
            self.response.out.write('Error rejecting: ' + str(e))
Example #56
0
class SetPromotionHandler(api_utils.PromoteDeal):
    '''
	A handler for activating a promotion. Will accept a users information and
		an identifier for a promotion. The types of promotions correspond to the
		identifiers returned in the FetchPromotionOptionsHandler
	'''
    @api_utils.validate(None,
                        'param',
                        user=True,
                        levrToken=True,
                        promotionID=True,
                        deal=True,
                        tags=False)
    @api_utils.private
    def post(self, *args, **kwargs):  #@UnusedVariable
        user = kwargs.get('actor')
        promotion_id = kwargs.get('promotionID')
        deal = kwargs.get('deal')
        self.tags = kwargs.get('tags', [])
        #		development = kwargs.get('development')

        try:
            # init super class
            super(SetPromotionHandler, self).__initialize__(deal, user)

            self.run_promotion(promotion_id, tags=self.tags, auto_put=True)

            # return success
            response = self.get_all_deals_response()
            api_utils.send_response(self, response, user)
        except AssertionError, e:
            self.send_error(str(e))
        except Exception, e:
            levr.log_error(e)
            self.send_error()
Example #57
0
class ConnectFacebookHandler(webapp2.RequestHandler):
    @api_utils.validate(None,
                        'param',
                        user=True,
                        remoteToken=True,
                        levrToken=True)
    @api_utils.private
    def post(self, *args, **kwargs):
        try:
            #RESTRICTED
            user = kwargs.get('actor', None)
            facebook_token = kwargs.get('remoteToken', None)

            user = social.Facebook(user, 'verbose')

            try:
                user, new_user_details, new_friends = user.first_time_connect(
                    facebook_token=facebook_token, )
            except Exception, e:
                levr.log_error()
                assert False, 'Could not connect with facebook.'

            logging.debug(levr.log_model_props(user))
            logging.debug(str(new_user_details))

            #return the user
            response = {
                'user': api_utils.package_user(user, True),
                'new_friends': [enc.encrypt_key(f) for f in new_friends],
                'new_user_details': new_user_details
            }
            api_utils.send_response(self, response, user)
        except AssertionError, e:
            levr.log_error()
            api_utils.send_error(self, '{}'.format(e.message))
Example #58
0
    def get(self, *args, **kwargs):
        '''
		A user (specified in ?uid=USER_ID) stops following the user specified in (/api/USER_ID/follow)
		If the user is not a follower and they request to unfollow, then nothing happens and success is true
		
		inputs: followerID(required)
		Output:{
			meta:{
				success
				errorMsg
				}
		'''
        try:
            logging.info('\n\nUSER REMOVE FOLLOWER')
            logging.debug(kwargs)
            user = kwargs.get('user')
            #			uid = user.key()
            actor = kwargs.get('actor')
            actorID = actor.key()
            private = kwargs.get('private')

            #PERFORM ACTIONS
            #grab a list of existing followers
            old_followers = user.followers
            logging.debug(old_followers)

            #check if in list of existing followers
            if actorID in old_followers:
                logging.debug('Follower exists')
                #create new list of followers that excludes the requested id
                new_followers = [u for u in old_followers if u != actorID]
                logging.debug(new_followers)

                #replace list of followers
                user.followers = new_followers

                #replace user that lost a follower
                db.put(user)
            else:
                logging.debug('follower does not exist. Do nothing')

            #respond
            api_utils.send_response(self, {}, actor)

        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')
Example #59
0
    def get(self, *args, **kwargs):  #@UnusedVariable
        '''
		inputs: lat,lon,limit
		Output:{
			meta:{
				success
				errorMsg
				}
			response:{
				[string,string]
				}
		'''
        try:
            pass
        except:
            levr.log_error()
            api_utils.send_error(self, 'Server Error')