Esempio n. 1
0
    def post(self):
        if self.request.path.startswith('/_checkin') and self.request.get('checkin'):
            # Parse floats as string so we don't lose lat/lng precision. We can use Decimal later.
            checkin_json = json.loads(self.request.get('checkin'),
                                      parse_float=str)
            user_id = checkin_json['user']['id']
            access_token = self.fetchAccessToken(user_id)
            if not access_token:
                logging.warning('Recieved push for unknown user_id {}'.format(user_id))
                return
            client = utils.makeFoursquareClient(access_token)
            return self.checkinTaskQueue(client, checkin_json)
        if self.request.path.startswith('/_warnings') and self.request.get('content'):
            content = json.loads(self.request.get('content'))
            access_token = content['access_token']
            client = utils.makeFoursquareClient(access_token)
            return self.warningTaskQueue(client, content)
        
        ## if self.this_is_a_homepost():
        ## return self.appHomePost
        ## else 
        ## return self.appBarPost

        client = utils.makeFoursquareClient()
        return self.appPost(client)
Esempio n. 2
0
  def getAllowedFriendsJson(self):
    userId = self.request.get('userId')
    checkinId = self.request.get('checkinId')
    token = self.request.get('access_token')

    access_token = self.verifiedAccessToken(userId, token)
    if (access_token):
      client = utils.makeFoursquareClient(access_token)
      checkin_json = self.getCoreCheckin(checkinId, client)
      venue_id = checkin_json['venue']['id']
      friends = client.users.friends()['friends']['items']
      allFriendIds = [friend['id'] for friend in friends if (friend.get('relationship', 'friend') == 'friend')]
      allowedFriendIds = self.getFriendTokens(userId, allFriendIds).keys()
      friendInfo = [
        {'name': (friend.get('firstName', '') + ' ' + friend.get('lastName', '')).strip(),
         'id': friend['id']}
         for friend in friends if friend['id'] in allowedFriendIds]
      friendInfoSorted = sorted(friendInfo, key=lambda x: x['name'].upper())

      if 'entities' in checkin_json:
        mentionedIds = [entity['id'] for entity in checkin_json['entities'] if entity['type'] == 'user']
      else:
        mentionedIds = []

      settingsSummary = self.getPermissionsSummary(userId)
      self.response.out.write(json.dumps({'friendInfo': friendInfoSorted,
                                          'mentions': mentionedIds,
                                          'settingsSummary': settingsSummary}))

    else:
      self.error(404)
Esempio n. 3
0
 def getUserIdFromToken(self, token):
   try:
     client = utils.makeFoursquareClient(token)
     user = client.users()['user']
     return user['id']
   except InvalidAuth:
     return None
Esempio n. 4
0
 def get(self):
     logging.info("I'm at AutoCompHomes")
     term = self.request.get('term')
     latlon = self.request.get('latlon')
     client = utils.makeFoursquareClient("IQBCPBQ5U3CFQI4DZCL3IC3TAAZMZXRUPJBHI0ZTG4B4LDLL")
     res = utils.search_venue(client, term, latlon)
     data = json.dumps(res)
     self.write(data)
    def post(self):
        if self.request.path.startswith('/_checkin') and self.request.get(
                'checkin'):
            # Parse floats as string so we don't lose lat/lng precision. We can use Decimal later.
            checkin_json = json.loads(self.request.get('checkin'),
                                      parse_float=str)
            user_id = checkin_json['user']['id']
            access_token = self.fetchAccessToken(user_id)
            if not access_token:
                logging.warning(
                    'Recieved push for unknown user_id {}'.format(user_id))
                return
            client = utils.makeFoursquareClient(access_token)
            return self.checkinTaskQueue(client, checkin_json)

        client = utils.makeFoursquareClient()
        return self.appPost(client)
Esempio n. 6
0
 def addRobotComment(self, cid, text, lcid=None, delete = True):
     oneNDun = utils.makeFoursquareClient(CONFIG['oneNDun_token'])
     try:
         if delete:
             self.deleteLastComment(oneNDun, cid, CONFIG['oneNDun_uid'], lcid)
         comment = oneNDun.checkins.addcomment(cid,params = {'text':text})
     except:
         return None
     return comment.get('comment').get('id')
	def get(self):
		client = utils.makeFoursquareClient()
		
		content_id = self.request.get('content_id')
		if content_id:
			content_info = ContentInfo.all().filter('content_id=', content_id).get()
			if not content_info:
				self.error(404)
				return
			return self.appGet(client)
Esempio n. 8
0
 def friendOneNDun(self, user, user_id): #user is the authed fs_user
     """Function for friending One-n-Dun! If the User allows in the setPrefs, 
         oneNDun can comment friendly reminders to his/her checkin!"""
     
     oneNDun = utils.makeFoursquareClient(CONFIG['oneNDun_token'])
     try:
         user.users.request(CONFIG['oneNDun_uid'])
         oneNDun.users.approve(user_id)
     except:
         return False
     return True
	def post(self):
		if self.request.path.startswith('/_checkin') and self.request.get('checkin'):
			# Parse floats as string so we don't lose lat/lng precision. We can use
				Decimal later.
			checkin_json = json.loads(self.request.get('checkin'),
									  parse_float=str)
			user_id = checkin_json['user']['id']
			access_token = self.fetchAccessToken(user_id)
			if not access_token:
				logging.warning('Received push for unknown user_id {}'.format(user_id))
				return
			client = utils.makeFoursquareClient(access_token)
			return self.checkinTaskQueue(client, checkin_json)
    def get(self):
        client = utils.makeFoursquareClient()

        content_id = self.request.get('content_id')
        if content_id:
            content_info = ContentInfo.all().filter('content_id =',
                                                    content_id).get()
            if not content_info:
                self.error(404)
                return
            return self.contentGet(client, content_info)

        return self.appGet(client)
Esempio n. 11
0
    def get(self):
        logging.info('*** We\'re at the OAuth get() place... ***')
        ##################################################
        ## This raises errors if the request f****d up!
        ##################################################
        try:
            error = self.request.get('error')
            if error == "access_denied":
                raise OAuthConnectDeniedException
            elif error:
                raise OAuthConnectErrorException

            ## Parses code if it exists... Don't change!
            code = self.request.get('code')
            logging.info('*** Code = {} ***'.format(code))
            if not code:
                raise OAuthConnectErrorException

            client = utils.makeFoursquareClient()
            access_token = client.oauth.get_token(code)
            logging.info('*** Access Token = {} ***'.format(access_token))
            if not access_token:
                logging.info('*** this didnt work, no access token! ***')
                raise OAuthConnectErrorException
            client.set_access_token(access_token)
        
        ## Useful handling for different types of errors.
        except OAuthConnectDeniedException:
            self.redirect(CONFIG['auth_denied_uri']) ## where?
            return
        except OAuthConnectErrorException:
            self.render('connect_error.html', name = CONFIG['site_name'])
            return
        
        #=======================================================================
        # Store or update the user in memcache, session, AND Database!
        #=======================================================================
        
        self.store_user(access_token) 
        
        ## Comment out untill we get a mobile url?
        #isMobile = utils.isMobileUserAgent(self.request.headers['User-Agent'])
        redirect_uri = CONFIG['auth_success_uri_desktop']
        logging.info('*** redirect_uri = {} ***'.format(redirect_uri))
        ## This will be where the main page renders!
        self.redirect(redirect_uri)
Esempio n. 12
0
    def get(self):
        ##################################################
        ## Clean up to use Sessions and not this Cookie
        ## Shit!!! Basicly write True or False depending
        ## on if we're authed... Maybe we don't need?
        ##################################################
        user = self.current_user
        is_authd = 'false'
        if user:
            client = utils.makeFoursquareClient(user['access_token'])
            try:
                client.users()
                is_authd = 'true'
            except InvalidAuth:
                self.logout()
        logging.info('*** is_authd = {} ***'.format(is_authd))

        self.write(is_authd)
Esempio n. 13
0
  def getUserSettingsJson(self):
    userId = self.request.get('userId')
    token = self.request.get('access_token')

    access_token = self.verifiedAccessToken(userId, token)
    if (access_token):
      client = utils.makeFoursquareClient(access_token)
      friends = [friend for friend in client.users.friends()['friends']['items']]
      friendInfo = [
        {'name': (friend.get('firstName', '') + ' ' + friend.get('lastName', '')).strip(),
         'id': friend['id']}
         for friend in friends if (friend.get('relationship', 'friend') == 'friend')]
      friendInfoSorted = sorted(friendInfo, key=lambda x: x['name'].upper())

      permissions = self.getPermissions(userId)
      self.response.out.write(json.dumps({'friendInfo': friendInfoSorted, 'permissions': permissions}))

    else:
      self.error(404)
Esempio n. 14
0
  def getAuthdStatus(self):

    # Allow cross domain access from http://www.herewithfriends.com and http://herewithfriends.appspot.com
    if (self.request.headers.get('Origin') == "http://www.herewithfriends.com"
        and self.request.headers.get('Host') == "herewithfriends.appspot.com"):
      self.response.headers.add_header("Access-Control-Allow-Origin", "http://www.herewithfriends.com")
      self.response.headers.add_header("Access-Control-Allow-Credentials", "true")

    elif (self.request.headers.get('Origin') == "http://herewithfriends.appspot.com"
          and self.request.headers.get('Host') == "herewithfriends.appspot.com"):
      self.response.headers.add_header("Access-Control-Allow-Origin", "http://herewithfriends.appspot.com")
      self.response.headers.add_header("Access-Control-Allow-Credentials", "true")

    user_token = UserToken.get_from_cookie(self.request.cookies.get('session', None))
    is_authd = False
    name = ''
    settingsSummary = ''
    settingsLink = ''
    if user_token is not None and user_token.fs_id:
      client = utils.makeFoursquareClient(user_token.token)
      try:
        user = client.users()['user']
        tokenId = user['id']
        if (tokenId != user_token.fs_id):
          is_authd = False
          user_token.delete()
        else:
          is_authd = True
          name = (user.get('firstName', '') + ' ' + user.get('lastName', '')).strip(),
          settingsSummary = self.getPermissionsSummary(user_token.fs_id)
          settingsLink = "%s/settings?userId=%s&access_token=%s" % (
                          utils.getServer(), user_token.fs_id, user_token.token)

      except InvalidAuth:
        user_token.delete()

    self.response.out.write(json.dumps({'connected': is_authd,
                                        'name': name,
                                        'settingsSummary': settingsSummary,
                                        'settingsLink' : settingsLink}))
Esempio n. 15
0
 def store_user(self, access_token, reset=False): #we might need something that 
     #=======================================================================
     # Function for storing user on first oauth. Oauth will check to see if 
     # user is in db, and if not, store them. This should happen ONLY once
     # so as not to overwrite set prefs! We'll use Memcache AND Session to 
     # Store! Update will update access token in all params! (??)
     #=======================================================================
     curr_client = utils.makeFoursquareClient(access_token)
     current_user = curr_client.users()
             
     if current_user:
         # Not an existing user so get user info
         # Store fs_id, token and prefs!
         profile = current_user['user']
         fs_id = profile["id"]
         
         existing_user_info = UserInfo.get_by_fs_id(fs_id)
         if existing_user_info and not reset:
             # User in DB we'll just update his/her access token!
             logging.info('*** There was an existing user with fs_id = {} ***'.format(fs_id))
             user = existing_user_info
             user.token = access_token
             prefs = json.loads(user.prefs)
             
             if not prefs.get('name'):
                 prefs['name'] = profile['firstName']
                 prefs['gender'] = profile['gender']
                 if not prefs.get('latlon'):
                     prefs['latlon'] = utils.get_latlon(current_user)
                 user.prefs = json.dumps(prefs)
         
         elif existing_user_info and reset:
             #user in db, but we want to reset to default prefs
             user = existing_user_info
             prefs = utils.make_default_prefs(curr_client,current_user)
             user.transactions = json.dumps([])
             user.prefs = json.dumps(prefs)
             user.token = access_token
                   
             
         else:
             logging.info('*** Creating a new user for fs_id = {} ***'.format(fs_id))
             user = UserInfo(fs_id = fs_id,
                             token = access_token)
             # store default prefs in user that can be reset later!
             prefs = utils.make_default_prefs(curr_client, current_user)
             
             
             user.transactions = json.dumps([])
             user.prefs = json.dumps(prefs)
             
         user.put() #make new user or update token of existing user!
         logging.info('****Added or updated User {} to DataBase!****'.format(user.fs_id))
         
         # Now store in Memcache and Session for later retrieval!
         udic = dict(fs_id = user.fs_id,
                     access_token = user.token,
                     gender=profile['gender'],
                     prefs = prefs)
         
         self.session["user"] = udic
         memcache.set('user_' + user.fs_id, udic)
         
     
     return self.session.get("user")
    def makeContentInfo(self,
                        checkin_json,
                        content,
                        url=None,
                        text=None,
                        photoId=None,
                        reply=False,
                        post=False):
        assert (reply ^ post), "Must pass exactly one of reply or post"
        assert (text or photoId)

        # Avoid posting duplicate content.
        request = ContentInfo.all()
        request = request.filter('checkin_id = ', checkin_json['id'])
        existing_contents = request.fetch(10)
        for existing_content in existing_contents:
            # Check that they're the same type of content
            if existing_content.reply_id and not reply:
                continue
            if existing_content.post_id and not post:
                continue
            # Check if the content payload is the same
            if existing_content.content == content:
                logging.info('Avoided posting duplicate content %s' % content)
                return existing_content

        content_id = utils.generateId()
        checkin_id = checkin_json['id']

        content_info = ContentInfo()
        content_info.content_id = content_id
        content_info.fs_id = checkin_json['user']['id']
        content_info.checkin_id = checkin_id
        content_info.venue_id = checkin_json['venue']['id']
        content_info.content = content
        if not url:
            url = self.generateContentUrl(content_id)

        access_token = self.fetchAccessToken(content_info.fs_id)
        client = utils.makeFoursquareClient(access_token)

        params = {'contentId': content_id, 'url': url}
        if text:
            params['text'] = text
        if photoId:
            params['photoId'] = photoId

        logging.info('creating content with params=%s' % params)

        if post:
            if CONFIG['local_dev']:
                content_info.post_id = utils.generateId()
            else:
                response_json = client.checkins.addpost(checkin_id, params)
                content_info.post_id = response_json['post']['id']
        elif reply:
            if CONFIG['local_dev']:
                content_info.reply_id = utils.generateId()
            else:
                response_json = client.checkins.reply(checkin_id, params)
                reply_id = None
                if 'replies' in response_json:
                    reply_id = response_json['replies']['id']
                elif 'reply' in response_json:
                    # Right now we return "replies" but we should probably return "reply"
                    # adding this so I don't have to do it later in the event we rename
                    reply_id = response_json['reply']['id']
                else:
                    logging.error(
                        "Could not find reply id in /checkins/reply response: %s"
                        % response_json)

                content_info.reply_id = reply_id

        content_info.put()

        return content_info
Esempio n. 17
0
  def makeContentInfo(self,
                      checkin_json,
                      content,
                      url=None,
                      text=None, photoId=None,
                      reply=False, post=False):
    assert (reply ^ post), "Must pass exactly one of reply or post"
    assert (text or photoId)

    # Avoid posting duplicate content.
    request = ContentInfo.all()
    request = request.filter('checkin_id = ', checkin_json['id'])
    existing_contents = request.fetch(10)
    for existing_content in existing_contents:
      # Check that they're the same type of content
      if existing_content.reply_id and not reply:
        continue
      if existing_content.post_id and not post:
        continue
      # Check if the content payload is the same
      if existing_content.content == content:
        logging.info('Avoided posting duplicate content %s' % content)
        return existing_content

    content_id = utils.generateId()
    checkin_id = checkin_json['id']

    content_info = ContentInfo()
    content_info.content_id = content_id
    content_info.fs_id = checkin_json['user']['id']
    content_info.checkin_id = checkin_id
    content_info.venue_id = checkin_json['venue']['id']
    content_info.content = content

    access_token = self.fetchAccessToken(content_info.fs_id)
    client = utils.makeFoursquareClient(access_token)

    if not url:
      params = {}
    else:
      params = {'contentId' : content_id,
                'url' : url}

    if text:
      params['text'] = text.encode('utf-8')
    if photoId:
      params['photoId'] = photoId

    logging.info('creating content with params=%s' % params)

    if post:
      if CONFIG['local_dev']:
        content_info.post_id = utils.generateId()
      else:
        response_json = client.checkins.addpost(checkin_id, params)
        content_info.post_id = response_json['post']['id']
    elif reply:
      if CONFIG['local_dev']:
        content_info.reply_id = utils.generateId()
      else:
        response_json = client.checkins.reply(checkin_id, params)
        reply_id = None
        if 'replies' in response_json:
          reply_id = response_json['replies']['id']
        elif 'reply' in response_json:
          # Right now we return "replies" but we should probably return "reply"
          # adding this so I don't have to do it later in the event we rename
          reply_id = response_json['reply']['id']
        else:
          logging.error("Could not find reply id in /checkins/reply response: %s" % response_json)

        content_info.reply_id = reply_id

    content_info.put()

    return content_info
Esempio n. 18
0
  def friendCheckinTaskQueue(self):
    userId = self.request.get('userId')
    checkinId = self.request.get('checkinId')
    token = self.request.get('access_token')

    access_token = self.verifiedAccessToken(userId, token)
    if (access_token):
      client = utils.makeFoursquareClient(access_token)

      selectedUserParam = self.request.get('selected')
      logging.debug('selected = %s' % selectedUserParam)
      selectedUserIds = selectedUserParam.split('-')

      checkin_json = self.getCoreCheckin(checkinId, client)
      venueId = checkin_json['venue']['id']
      sourceName = checkin_json['user']['firstName']
      sourceId = checkin_json['user']['id']
      if (sourceId != userId):
        logging.error("User %s attempted to access checkin for user %s" % (userId, sourceId))
        self.error(400)
        return
      successComment = 'Check-in by %s.' % sourceName.encode('utf-8')
      newCheckin = dict({'venueId': venueId, 'broadcast': 'public', 'shout': successComment})
      if 'event' in checkin_json:
        newCheckin['eventId'] = checkin_json['event']['id']

      friends = client.users.friends()['friends']['items']
      allFriendIds = [friend['id'] for friend in friends if (friend.get('relationship', 'friend') == 'friend')]
      allowedFriendTokens = self.getFriendTokens(userId, allFriendIds)

      successNames = []
      disconnectedNames = []

      for selectedUserId in selectedUserIds:
        matching = [friend for friend in friends if friend['id'] == selectedUserId]
        token = allowedFriendTokens.get(selectedUserId)
        if (len(matching) > 0 and token is not None):
          friendObj = matching[0]
          client.set_access_token(token)
          try:
            friendCheckin = client.checkins.add(newCheckin)['checkin']
            if 'user' not in friendCheckin:
              friendCheckin['user'] = {'id': friendObj['id'], 'firstName': friendObj['firstName']}
            successNames.append(friendObj['firstName'])

            # Update history
            history = CheckinHistory()
            history.source_fs_id = sourceId
            history.target_fs_id = friendObj['id']
            history.target_fs_name = (friendObj.get('firstName', '') + ' ' + friendObj.get('lastName', '')).strip()
            history.put()

            ## successComment moved to shout instead of post due to complaints
            # self.makeContentInfo( checkin_json = friendCheckin,
            #                       content = json.dumps({'checkinFrom': sourceName}),
            #                       text = successComment,
            #                       post = True)
          except InvalidAuth:
            # If a user disconnects the app, we can then have an invalid token
            logging.info('invalid oauth - deleting token for %s' % friendObj['id'])
            disconnectedNames.append(friendObj['firstName'])
            tokenObj = UserToken.get_by_fs_id(selectedUserId)
            if (tokenObj is not None):
              tokenObj.delete()
              memcache.delete('token:%s' % selectedUserId)

          except Exception as inst:
            logging.error('Failed to check in user %s-%s: %s' % (friendObj['firstName'], friendObj['id'], str(inst)))

      client.set_access_token(access_token) # restore token to original user
      successNamesStr = ", ".join(successNames)
      disconnectedNamesStr = ", ".join(disconnectedNames)

      if (len(successNames) > 0):
        message = "You just checked in: %s" % successNamesStr
        self.makeContentInfo( checkin_json = checkin_json,
                              content = json.dumps({'successNames': successNames, 'message': message}),
                              text = message,
                              post = True)

      if (len(disconnectedNames) > 0):
        message = "Failed to check in the following users as they have disconnected the app: %s" % disconnectedNamesStr
        self.makeContentInfo( checkin_json = checkin_json,
                              content = json.dumps({'disconnectedNames': disconnectedNames, 'message': message}),
                              text = message,
                              post = True)

      logging.info('%s (%s) checked in: %s' % (sourceName, sourceId, successNamesStr))
      self.response.out.write(json.dumps({'successNames': successNames}))