Пример #1
0
 def post(self):  # should run at most 1/s due to entity group limit
     """
 Task Worker to mark place as updated
 Params:
   placeId: string place Id
   userId: string
 """
     try:
         logging_ext.log_to_console("AddPlaceChangesWorker")
         place_id_str = self.request.get('placeId')
         user_id_str = self.request.get('userId')
         place_entries = Change.\
           query(Change.kind==Change.CHANGE_PLACE, Change.recordId == place_id_str)
         now = datetime.now()
         for p in place_entries:
             if p.when < now:
                 p.when = now
                 p.put()
         user = User.get_by_id(int(user_id_str))
         friends_key_list = user.get_friends_key_list()
         for user_key in friends_key_list:
             p = Change.\
               query(
               Change.kind == Change.CHANGE_PLACE,
                 Change.subscriberId == str(user_key.id()),
                 Change.recordId == place_id_str).get()
             if not p:
                 p = Change()
                 p.kind = Change.CHANGE_PLACE
                 p.subscriberId = str(user_key.id())
                 p.placeId = place_id_str
             p.when = now
             p.put()
     except:
         logging_ext.error('** AddPlaceChangesWorker', exc_info=True)
Пример #2
0
def serialize_user_details(user_id, places_ids, current_user, request, since=None):
  """ give the list of votes & places_ids for a user
  @param user_id: int: which user
  @param places_ids: dict: list of places_ids indexed by key (BY VALUE)
  @param current_user: int: current user - if same as user_id then
    we exclude untried
  @return:
  """
  try:
    logging.info("serialize_user_details 1")
    # get it from the cache
    user_id = int(user_id)
    votes = Vote.query(Vote.voter == user_id)
    user = User.get_by_id(user_id)
    user_profile = user.profile()
    if getProp(user_profile, 'last_write'):
      last_write = user_profile.last_write
    else:
      last_write = None
    result = {"votes": votes,
              "id": user_id,
              # todo is it first_name?
              'name': user_profile.screen_name,
              'last_write': last_write}
    if votes:
      logging.debug("serialize_user_details: %d votes"%len(votes))
      for place_key in votes:
        if not place_key in places_ids:
          place_json = Item.id_to_json(place_key)
          # if user_id == current_user:
          #   place_json['vote'] = votes[place_key]['vote']
          if "category" in place_json:
            places_ids[place_key] = place_json
      for place_id in places_ids:
        pl = ndb.Key(Item,place_id).get()
        json_data = pl.get_json()
        places_ids[place_id] = json_data
      logging.debug('serialize_user_details: Added %d places_ids'%len(places_ids))
    else:
      logging.debug("serialize_user_details: No Votes")
    return result
  except Exception, e:
    logging_ext.error("serialize_user_details Exception", exc_info=True)
Пример #3
0
 def post(self):  # should run at most 1/s due to entity group limit
     """
 Task Worker to mark votes as updated
   - deletes all entries for the vote
   - adds a new one for all friends of voter
 Params:
   voteId: string
   userId: string
 """
     try:
         logging_ext.log_to_console('AddVoteChangesWorker IN')
         vote_id_str = self.request.get('voteId')
         if not vote_id_str:
             logging_ext.error("** AddVoteChangesWorker: no vote id")
             return
         user_id_str = self.request.get('userId')
         if not user_id_str:
             logging_ext.error("** AddVoteChangesWorker: no user_id")
             return
         user_id = int(user_id_str)
         me = User.get_by_id(user_id)
         time = self.request.get('time')
         old_votes = Change.\
           query(Change.kind == Change.CHANGE_VOTE, Change.recordId == vote_id_str).\
           fetch(keys_only=True)
         ndb.delete_multi(old_votes)
         friends_list = me.get_friends_key_list()
         for u in friends_list:
             change = Change()
             change.kind = Change.CHANGE_VOTE
             change.recordId = vote_id_str
             change.subscriberId = str(u.id())
             change.when = datetime.strptime(
                 time, views.config['DATETIME_FORMAT'])
             change.put()
     except Exception:
         logging_ext.error("** AddVoteChangesWorker", exc_info=True)
Пример #4
0
  def get(self):
    """ get the entire user record, including friends' places """
    try:
      if self.user.blocked:
        raise Exception('Blocked')
      my_id = self.user_id

    except:
      logging_ext.error('getFullUserRecord: User Exception')
      json.dump({'result':'FAIL'},
                  self.response.out,
                  default=json_serial)
      return

    if my_id:
      #profile_in("getFullUserRecord")
      user = User.get_by_id(my_id)
      if user:
        # logged in
        since = None
        if 'since' in self.request.params:
          # move since back in time to allow for error
          since = datetime.datetime.strptime(
            self.request.params['since'],
            config['DATETIME_FORMAT']) - \
                  config['TIMING_DELTA']
        # is it for a specific user?
        if "forUser" in self.request.params:
          for_1_user = long(self.request.get("forUser"))
        else:
          for_1_user = None

        # either the first lookup is for me, plus everyone,
        # or it is for a specified user
        result = {
          "id": my_id,
          "admin": self.user.profile().is_admin }
        if for_1_user:
          logging.info("getFullUserRecord: 1 user")
          first_user = for_1_user
          result["for_1_user"] = for_1_user
        else:
          logging.info("getFullUserRecord: 1+ user")
          first_user = my_id
        dict_id_place = {}
        # load the data for the 1 user  - me or specified
        friends_data = [
          serialize_user_details(
            first_user,
            dict_id_place,
            my_id,
            self.request,
            since)]
        # was it for all users? If so we've only done ourselves
        if not for_1_user:
          # for all users
          prof = user['p']
          if config['all_are_friends']:
            q = User.gql('')
            logging.info("getFullUserRecord: %d friends"%q.count())
            for user in q:
            # for userProf in UserProfile().all():
              if user.get_id() == my_id:
                continue  # don't add myself again
              data = serialize_user_details(
                user.get_id(), dict_id_place, my_id, self.request, since)
              logging.info("getFullUserRecord: record %s"%data)
              friends_data.append(data)
          else:
            for friend in prof.friends:
              friends_data.append(serialize_user_details(
                friend, dict_id_place, my_id, self.request, since))
          result["friendsData"] = friends_data
          logging.debug('getFullUserRecord: return %d places'%len(dict_id_place))
        result["places"] = dict_id_place
        # encode using a custom encoder for datetime

        json_str = json.dumps(
          result,
          default=json_serial)
        self.response.out.write(json_str)
        #profile_out("getFullUserRecord")
        return
    self.error(401)
Пример #5
0
  def get(self):
    """ get the user record, including friends' places """
    try:
      if self.user.blocked:
        raise Exception('Blocked')
      my_id = self.user_id

    except:
      logging_ext.error('getFullUserRecord: User Exception')
      json.dump({'result':'FAIL'},
                  self.response.out,
                  default=json_serial)
      return

    if my_id:
      user = User.get_by_id(my_id)
      if user:
        # logged in
        result = {
          "id": my_id,
          "admin": self.user.profile().is_admin }
        since = None
        if 'since' in self.request.params:
          # move since back in time to allow for error
          since = datetime.datetime.strptime(
            self.request.params['since'],
            config['DATETIME_FORMAT']) - \
                  config['TIMING_DELTA']
        user_list = []
        user_results = []
        # is it for a specific user?
        if "forUser" in self.request.params:
          user_list.append(user.get(self.request.params['forUser']))
        else:
          if config['all_are_friends']:
            q = User.gql('')
            for user in q:
              user_list.append(user)
        places = {}
        my_votes = Vote.query(Vote.voter==my_id)
        for u in user_list:
          user_id = u.get_id()
          if user_id == my_id:
            votes = my_votes
          else:
            votes = Vote.query(Vote.voter==u.get_id())
          for v in votes:
            #add to the list if it's not there, or overwrite if this is my version
            if not v in places or user_id == my_id:
              places [v] = Item.id_to_json(v)

          user_profile = u.profile()
          if getProp(user_profile, 'last_write'):
            last_write = user_profile.last_write
          else:
            last_write = None
          user_str = {"votes": votes,
              "id": u.get_id(),
              # todo is it first_name?
              'name': u.screen_name,
              'last_write': last_write}
          user_results.append(user_str)

        result["places"] = places
        result["friendsData"] = user_results
        json_str = json.dumps(
          result,
          default=json_serial)
        self.response.out.write(json_str)
        #profile_out("getFullUserRecord")
        return
    self.error(401)