Exemplo n.º 1
0
 def getBadge(self):
         returnBadge=5
         existingBadge=UserBadge.gql('WHERE user = :1 and badge = :2', self.user, returnBadge).get()
         if existingBadge is  not None:
                 logging.info('Already assigned 5 day usage badge. Skipping.')
                 return None
         if self.version is None:
                 logging.info('Older version of addon not usage badge defined!')
                 return None
         yesterday=datetime.datetime.now().date() - datetime.timedelta(days=1)
         limit=datetime.datetime.now().date() - datetime.timedelta(days=4)
         active=True
         while yesterday >= limit:
                s=SessionModel.gql('WHERE date = :1 and instaright_account = :2', yesterday, self.user).get()
                if s is None:
                         logging.info('user %s NOT active for date %s' %(self.user, yesterday))
                         active=False
                         return None
                else:
                         logging.info('user %s active for date %s' %(self.user, yesterday))
                yesterday-=datetime.timedelta(days=1)
         if active:        
                 logging.info('user %s has been active in last %s' %(self.user, returnBadge))
                 return '5'
         logging.info('usage badge %s: not initialized' %self.user)
Exemplo n.º 2
0
        def get(self, _date):
                dt = datetime.datetime.strptime(_date, '%Y-%m-%d').date()
                if dt is None:
                        dt = datetime.datetime.now().date()
                logging.info('checking badges for date: %s' % str(dt))
                stats = UserBadge.gql('WHERE date = :1 ', dt).fetch(1000)
                if not stats:
                        self.response.out.write('no badges found for date %s Retreived no data' % _date)
                        return
                badges = [(s.user, s.badge) for s in stats]

                template_variables = {'badges': badges}
        	path= os.path.join(os.path.dirname(__file__), 'templates/badges.html')
                self.response.headers["Content-type"] = "text/html"
        	self.response.out.write(template.render(path,template_variables))
Exemplo n.º 3
0
        def get(self):
                #redirect from appengine domain
                self.redirect_perm()
                self.get_user()

                if self.user_uuid is None or len(str(self.user_uuid)) == 0 or self.screen_name is None or self.user_detail_key is None:
                        logging.info('No cookies, redirecting to home page')
                        self.redirect('/?redirect=/user/dashboard&show_login=1')
                        return
                logging.info('user: %s' %self.instaright_account)
                sessions = SessionModel.gql('WHERE instaright_account = :1 ORDER by date desc ' , self.instaright_account).fetch(self.link_batch)

                score = 0
                links = None
                if sessions is not None:
                        links = [ s for s in sessions if s is not None ]
                ud_key=db.Key(self.user_detail_key)
                logging.info('user detail key %s' % self.user_detail_key)
                template_variables=[]
                now=datetime.datetime.now().date()
                #start_of_week= time.asctime(time.strptime('%s %s 1' %(now.year, now.isocalendar()[1]), '%Y %W %w'))
                start_of_week= datetime.datetime.strptime('%s %s 1' %(now.year, now.isocalendar()[1]), '%Y %W %w')
                memcache_key='user_'+self.user_detail_key+'_score'
                cached_score=memcache.get(memcache_key)
                if cached_score is not None:
                        logging.info('got score from cache( %s ): %s' %( memcache_key, cached_score ))
                        score=cached_score
                else:
                        logging.info('parameters: start of week %s now %s for user_key %s ' % ( start_of_week,now, ud_key))
                        score_entities = ScoreUsersDaily.gql('WHERE user = :1 and date >= :2', ud_key, start_of_week).fetch(100)
                        #score_entities = ScoreUsersDaily.gql('WHERE user = :1 and date <= :2 and date >= :3', ud_key, now , start_of_week).fetch(100)
                        logging.info('got %s score entities' % len(score_entities))
                        if score_entities is not None:
                                scores = [ s.score for s in score_entities if s is not None ]
                                score=sum(scores)

                        logging.info('calculated score : %s' % score )
                        exp_ts=time.mktime((datetime.datetime.now() + datetime.timedelta(days=1)).timetuple())
                        memcache.set(memcache_key, score, time=exp_ts)
                badges = None
                all_badges = UserBadge.gql('WHERE user = :1 order by date desc', self.instaright_account).fetch(1000)
                if all_badges is not None:
                        badges = set([ (b.badge, b.badge_property.badge_desc) for b in all_badges if b is not None and b.badge_property is not None ])
                template_variables = {'user':self.screen_name, 'avatar':self.avatar,'instaright_account':self.instaright_account,'facebook_token':self.facebook_oauth_token,'facebook_profile': self.facebook_profile, 'twitter_profile': self.twitter_profile, 'twitter_token': self.twitter_oauth_token, 'google_profile': self.google_profile, 'google_token':self.google_oauth_token, 'picplz_profile': self.picplz_name, 'picplz_token': self.picplz_oauth_token, 'evernote_profile': self.evernote_name, 'evernote_token': self.evernote_oauth_token, 'links':links, 'score': score, 'visible_items_num': self.link_batch, 'badges': badges,'logout_url':'/account/logout'}
                logging.info('templates %s' %template_variables)
                path= os.path.join(os.path.dirname(__file__), 'templates/user_info.html')
                self.response.headers["Content-type"] = "text/html"
		self.response.out.write(template.render(path,template_variables))
Exemplo n.º 4
0
        def post(self):
                user=self.request.get('user', None)
                url=self.request.get('url', None)
                domain=self.request.get('domain', None)
                version=self.request.get('version', None)
                client=self.request.get('client', None)
                badge=None
                if user is None:
                        logging.info('unknown user skipping')
                        return
                user_details = UserDetails.gql('WHERE instaright_account = :1', user).get()
                if user_details is None:
                        user_details = UserDetails()
                        user_details.instaright_account = user
                        user_details.put()
                client_badge = UserBadge.gql('WHERE badge = :1 and user = :2', client, user).get()
                if client_badge is None:
                        badge = Badges.gql('WHERE badge_label = :1' , client).get()
			if badge is None:
                        	mail.send_mail(sender='*****@*****.**', to='*****@*****.**', subject='Unknown client!', html='user %s saved link %s using unrecognised client %s' %( user,url, client ), body='user %s saved link %s using unrecognised client %s' %( user,url, client))
				return
                        client_badge = UserBadge()
                        client_badge.badge = client
                        client_badge.badge_property = badge.key()
                        client_badge.date = datetime.datetime.now().date()
                        client_badge.user = user
                        client_badge.user_property = user_details.key()
                        client_badge.put()
                if version is not None and len(version) == 0:
                        version = None
                currentBadge = memcache.get('badge_'+user)
                if currentBadge is not None and (currentBadge == '1' or currentBadge == '2' or currentBadge == '3' or currentBadge == '5'):
                        logging.info('for user %s already using full day badge: %s' %(user,currentBadge))
                        return
                badger=BadgeUtil.getBadger(user, url, domain, version)
                if badger is None:
                        logging.info('no badger initialized. skipping')
                        return
                badge=badger.getBadge()
                if badge is not None:
                        # midnight timestamp - memcache expiration 
                        midnight=datetime.datetime.now().date() + datetime.timedelta(days=1)
                        midnight_ts=time.mktime(midnight.timetuple())
                        memcache.set('badge_'+user, badge, time=midnight_ts)
                        logging.info('setting badge cache: %s for user badge_%s valid until midnight %s' % (badge,user,midnight_ts))
                        existingBadge=UserBadge.gql('WHERE badge = :1 and user = :2 and date = :3', badge, user, datetime.datetime.now().date()).get()
                        if existingBadge is not None:
                                self.response.out.write('request processed')
                                return
                        b = Badges.gql('WHERE badge_label = :1' , badge).get()
                        if b is None:
                                b = Badges()
                                b.badge_label = badge
                                b.badge_icon = badge
                                b.put()
                        userBadge=UserBadge()
                        userBadge.user=user
                        userBadge.badge=badge
                        userBadge.badge_property = b.key()
                        userBadge.user_property = user_details.key()
                        userBadge.put()
			
                UserScoreUtility.updateBadgeScore(user, badge)
Exemplo n.º 5
0
	def getUserDetails(self, request_handler):
		
		#google_login_url = users.create_login_url('/') 
	        #twitter_logout_url = '/oauth/twitter/logout'

                twitter_cookie = request_handler.request.cookies.get('oauth.twitter')
        	evernote_user = OAuthClient('evernote', request_handler)
        	flickr_user = OAuthClient('flickr', request_handler)

                #return variables
        	screen_name=None
                avatar=None
		auth_service=None
		user_details_key=None

                instaright_account=None
		# used to connect user details with session
                evernote_username=None
                flickr_username=None

		google_user = users.get_current_user()
		#logging.info('trying to connect with fb key %s secret %s' %( self.facebook_key, self.facebook_secret))
        	facebook_user = facebook.get_user_from_cookie(request_handler.request.cookies, self.facebook_key, self.facebook_secret)
                facebook_access_token=None
                existing_user = None
        	if google_user:
			existing_user= UserDetails.gql('WHERE google_profile=\'%s\'' %google_user.email()).get()
			existing_user_by_mail = UserDetails.gql('WHERE mail=\'%s\'' %google_user.email()).get()
                        if self.ud is None and existing_user is not None:
                                self.ud = existing_user
                                if self.ud.mail is None:
                                        self.ud.mail = google_user.email()
                        #TODO what is both are not None and pointing to different entities
                        if existing_user is not None and existing_user_by_mail is not None and str(existing_user.key()) != str(existing_user_by_mail.key()):
                                logging.error('data inconsistancy for google user %s ' % google_user.email())
                        #NOTE: data consistency 
			if existing_user is None and existing_user_by_mail is not None:
                                existing_user_by_mail.google_profile = google_user.email()
                                existing_user_by_mail.put()
                                existing_user = existing_user_by_mail
                        if existing_user is None:
                                #TODO update google profile
				existing_user = UserDetails()
				existing_user.mail=google_user.email()
                                existing_user.google_profile=google_user.email()
                        elif existing_user.avatar is not None:
                                avatar = existing_user.avatar
				existing_user.mail=google_user.email()
                        existing_user.put()

			auth_service='google'
                	screen_name=google_user.nickname()
			user_details_key=existing_user.key()

			user_signup_badge = UserBadge.gql('WHERE user_property = :1 and badge = :2', existing_user.key(),'signup').get()
                        if user_signup_badge is None:
                                user_badge = UserBadge()
                                user_badge.user = screen_name
                                user_badge.badge = 'signup'
                                badge = Badges.gql('WHERE badge_label = :1', 'signup').get()
                                user_badge.badge_property = badge.key()
                                user_badge.user_property = existing_user.key()
                                user_badge.put()
                        instaright_account=existing_user.instaright_account
                if twitter_cookie is not None and len(twitter_cookie) > 0:
			try:
                        	twitter_user = OAuthClient('twitter', request_handler)
				info = twitter_user.get('/account/verify_credentials')
				profile_image_url = "%s" %info['profile_image_url']
				existing_user = UserDetails.gql('WHERE twitter = \'http://twitter.com/%s\'' % screen_name).get()
				if existing_user is None:
					logging.info('new twitter user login %s' % screen_name)
					existing_user=UserDetails()
					existing_user.twitter='http://twitter.com/%s' %screen_name
					existing_user.avatar = profile_image_url
				else:
					logging.info('existing twitter user login %s' % screen_name)
					if existing_user.avatar is None:
						existing_user.avatar = profile_image_url
                                        else:
                                                avatar = existing_user.avatar
                                existing_user.put()
				user_details_key=existing_user.key()
                                twitter_cookie = request_handler.request.cookies.get('oauth.twitter')
                                twitter_oauth = OAuthAccessToken.get_by_key_name(twitter_cookie)
                                if twitter_oauth is not None and existing_user is not None:
                                        twitter_token = twitter_oauth.oauth_token
                                        twitter_secret= twitter_oauth.oauth_token_secret
                                        taskqueue.add(url='/util/twitter/get_friends', params={'user_details_key': str(existing_user.key()),'user_token':twitter_token, 'user_secret': twitter_secret})
                                if screen_name is None:
                		        screen_name = "%s" % info['screen_name']
                                        avatar=profile_image_url
				        auth_service='twitter'
                                logging.info('updating user score ...')
			        user_signup_badge = UserBadge.gql('WHERE user_property = :1 and badge = :2', existing_user.key(),'signup').get()
                                if user_signup_badge is None:
                                        user_badge = UserBadge()
                                        user_badge.user = screen_name
                                        user_badge.badge = 'signup'
                                        badge = Badges.gql('WHERE badge_label = :1', 'signup').get()
                                        user_badge.badge_property = badge.key()
                                        user_badge.user_property = existing_user.key()
                                        user_badge.put()
                                instaright_account=existing_user.instaright_account
			except:
				e0,e = sys.exc_info()[0], sys.exc_info()[1]
                                logging.info('got error while using twitter oauth: %s => %s' %(e0, e))
        	if facebook_user:
                	graph = facebook.GraphAPI(facebook_user["access_token"])
			try:
                		profile = graph.get_object("me")
				profile_link=profile["link"]
				profile_id=profile["id"]
                		friends = graph.get_connections("me", "friends")
				existing_user=UserDetails.gql('WHERE facebook = \'%s\'' % profile_link).get()
				if existing_user is not None:
					logging.info('existing facebook logging %s' % profile_link)
					existing_user.facebook=profile_link
					existing_user.facebook_friends=simplejson.dumps(friends)
					existing_user.facebook_profile=profile["name"]
					existing_user.facebook_id=profile_id
					if existing_user.avatar is None:
						existing_user.avatar = avatar
                                        else:
                                                avatar = existing_user.avatar
					existing_user.put()
				else:
					logging.info('new facebook logging %s' % profile_link)
					existing_user=UserDetails()
					existing_user.facebook=profile_link
					existing_user.facebook_profile=profile["name"]
					existing_user.facebook_friends=simplejson.dumps(friends)
					existing_user.facebook_id=profile_id
					existing_user.avatar = avatar
					existing_user.put()
                                if screen_name is None:
                		        screen_name = profile["name"]
				        auth_service='facebook'
                                        avatar=existing_user.avatar
				user_details_key=existing_user.key()
			        user_signup_badge = UserBadge.gql('WHERE user_property = :1 and badge = :2', existing_user.key(),'signup').get()
                                if user_signup_badge is None:
                                        user_badge = UserBadge()
                                        user_badge.user = screen_name
                                        user_badge.badge = 'signup'
                                        badge = Badges.gql('WHERE badge_label = :1', 'signup').get()
                                        user_badge.badge_property = badge.key()
                                        user_badge.user_property = existing_user.key()
                                        user_badge.put()
                                instaright_account=existing_user.instaright_account
                                facebook_access_token=facebook_user["access_token"]
			except:
				e0,e = sys.exc_info()[0], sys.exc_info()[1]
				logging.info('error validating token %s === more info: %s' %(e0,e))
		
                if evernote_user.get_cookie() is not None and len(evernote_user.get_cookie()) > 0:
                        logging.info('evernote token active: %s' % evernote_user)
                        logging.info('evernote access token id: %s' % evernote_user.get_cookie())
                        evernote_access = evernote_user.get_cookie()
                        access_token = OAuthAccessToken.get_by_key_name(evernote_access)
                        if access_token is not None and access_token.service == 'evernote':
                                evernote_username = access_token.specifier
                                if existing_user is not None:
                                        existing_user.evernote_profile = evernote_username
                                        existing_user.put()
                        
                if flickr_user.get_cookie() is not None and len(flickr_user.get_cookie()) > 0:
                        logging.info('flickr token active: %s' % flickr_user)
                        logging.info('flickr access token id: %s' % flickr_user.get_cookie())
                        flickr_access = flickr_user.get_cookie()
                        access_token = OAuthAccessToken.get_by_key_name(flickr_access)
                        if access_token is not None and access_token.service == 'flickr':
                                flickr_username = access_token.specifier
                                if existing_user is not None:
                                        existing_user.flickr_profile = flickr_username
                                        existing_user.put()

		log_out_cookie = request_handler.request.cookies.get('user_logged_out')
		path=request_handler.request.path
		logging.info('path: %s' %path)
		#reset logout cookie in case of /account url
		if log_out_cookie and path == '/account':
			logging.info('deleting logout cookie')
                        expires = datetime.datetime.now()
                        exp_format = datetime.datetime.strftime(expires, '%a, %d-%b-%Y %H:%M:%S GMT')
			request_handler.response.headers.add_header('Set-Cookie', 'user_logged_out=%s; expires=%s; path=/' %( '0', exp_format))
			
		logging.info('user auth with %s: %s' %(auth_service, screen_name))
                if screen_name is not None and screen_name not in self.skip_list:
                        logging.info('user %s not in skip list %s ... sending mail' %(screen_name, str(self.skip_list)))
                        mail.send_mail(sender='*****@*****.**', to='*****@*****.**', subject='User sign up!', html='Awesome new user(%s) signed up: %s <br>avatar <a href="%s"><img src="%s" width=20 height=20 /></a>' %(auth_service, screen_name , avatar, avatar), body='Awesome new user(%s) signed up: %s avatar %s' %(auth_service, screen_name, avatar))
                                        
                user_details = {'screen_name':screen_name, 'auth_service':auth_service, 'user_details_key':user_details_key, 'avatar':avatar, 'instaright_account':instaright_account,'facebook_access_token': facebook_access_token, 'evernote_name': evernote_username, 'flickr_name': flickr_username}
		logging.info('[utils] user details:%s' % user_details)
		return user_details