Example #1
0
 def get(self, id):
   """
   get an Item
   :param id: int
   :return: string json
   """
   try:
     it = Item.get_by_id(int(id))
     res = {"place_name": it.place_name,
            "address": it.address,
            "cuisineName": it.category.title,
            "lat": str(it.lat),
            "lng": str(it.lng),
            "id": it.key.id()
     }
     if it.photo:
       res["img"] = it.key.id()
     if it.owner == self.user_id:
       res["mine"] = True
       res["descr"], res["stars"], res["untried"] = it.vote_from(it.owner)
     else:
       res["mine"] = False
       res["descr"], res["stars"], res["untried"] = it.vote_from(self.user_id)
     json.dump(res, self.response.out)
   except Exception:
     logging_ext.error("getItem_ajax Exception", exc_info=True)
     self.error(500)
Example #2
0
def update_votes(item, request_handler, user_id):
  """
  save the vote for an item
  :param item: {Item}
  :param request_handler: {BaseHandler} for the request
  :param user_id: {int}
  """
  try:
    old_votes = Vote.query(Vote.voter == user_id, Vote.item == item.key)
    for v in old_votes:
      v.key.delete()
    vote = Vote()
    vote.item = item.key
    vote.voter = user_id
    vote.comment =  unicode(request_handler.request.get('myComment'))
    vote.meal_kind =  int(request_handler.request.get('kind'))
    vote.place_style=  int(request_handler.request.get('style'))
    vote.cuisine = Category.get_by_id(request_handler.request.get('cuisine')).key
    vote_stars = int(request_handler.request.get("voteScore"))
    vote.stars = vote_stars
    if vote_stars == 0:
      vote_untried= bool(request_handler.request.get("voteUntried"))
    else:
      vote_untried = False
    vote.untried = vote_untried
    vote.put()
    ndb_models.mark_vote_as_updated(str(vote.key.id()), user_id)
    logging.info ('update_votes for %s "%s"=%d'%
                  (item.place_name,vote.comment,vote.stars))

  except Exception, ex:
    logging_ext.error("newOrUpdateItem votes exception", exc_info=True)
    raise
Example #3
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)
Example #4
0
 def post(self):
     try:
         user_id_str = self.request.get('userId')
         before = datetime.now().strftime(views.config['DATETIME_FORMAT'])
         taskqueue.add(url='/api/ClearUserChanges', params={})
     except:
         logging_ext.error('** ClearUserUpdates', exc_info=True)
Example #5
0
  def get(self):
    place_id = self.request.params['place_id']
    logging.debug('getPlaceDetailsApi '+place_id)
    params = {'placeid': place_id,
              'key': config['google_api_key']}
    url = "https://maps.googleapis.com/maps/api/place/details/json?" + \
          urllib.urlencode(params)
    res = {}
    try:
      response = urllib2.urlopen(url)
      json_result = response.read()
      details_result = json.loads(json_result)
    except:
      logging_ext.error(
        'getPlaceDetailFromGoogle: Exception [%s]',
        place_id,
        exc_info=True)
      return {"photo": None, "telephone": None}

    if details_result['status'] == "OK":
      if "international_phone_number" in details_result['result']:
        res['telephone'] = details_result['result']["international_phone_number"]
      if "website" in details_result['result']:
        res['website'] = details_result['result']["website"]
    json.dump(res, self.response.out)
Example #6
0
 def get(self, key):
   """
   " get a single item
   """
   try:
     json.dump(Item.id_to_json(key), self.response.out)
   except:
     logging_ext.error('updateItem GET Exception '+key,exc_info=True)
Example #7
0
 def get(self, key):
   try:
     photo = ndb.Key(urlsafe=key).get()
     if photo:
       self.response.headers['Content-Type'] = 'image/png'
       self.response.out.write(photo.picture)
   except:
     logging_ext.error('ImageHandler '+key, exc_info=True)
Example #8
0
def check_good_server_version(request):
  good_version = False
  if 'version' in request.params:
    version = float(request.params['version'])
    min_version = ndb_models.Config.min_server_version_allowed()
    if version >= float(min_version):
      return True
  if not good_version:
    logging_ext.error("check_good_server_version BAD VERSION")
    return False
Example #9
0
    def get_google_db_places(cls, lat, lng, name, radius):
        """
    do a google geo search
    :param lat: float
    :param lng: float
    :param name: string - to look for
    :param radius: int - search radius (m)
    :return: dict - {"item_count": int, "items": []}
    """
        results = {"item_count": 0, "items": []}
        try:
            # remove AND or & from name
            search_words = cls.get_word_list(name)
            search_text_or = "|".join(search_words)
            search_text_and = " ".join(search_words)
            escaped_name = "%s%%7C%s" % (urllib2.quote(search_text_or),
                                         urllib2.quote(search_text_and))
            url = ("https://maps.googleapis.com/maps/api/place/nearbysearch/"
                  "json?rankby=distance&types=%s&location=%f,%f&name=%s&sensor=false&key=%s")\
                  % \
                  (settings.config['place_types'],
                   lat,
                   lng,
                   escaped_name,
                   settings.config['google_api_key'] )
            addresses = []
            response = urllib2.urlopen(url, timeout=15)
            jsonResult = response.read()
            addressResult = json.loads(jsonResult)
            logging.info("get_google_db_places: Url=%s" % url)

        except Exception, e:
            if settings.running_on_test_server():
                # make up a test
                print "get_google_db_places OFFLINE - Making Up Fake Data"
                addressResult = {
                    'status':
                    'OK',
                    'results': [{
                        'formatted_address': '1 Crouch Hill, London',
                        'name': 'A Madeup Place',
                        'place_id': '0',
                        'geometry': {
                            'location': {
                                'lat': 54.0 + random(),
                                'lng': -(1.0 + random())
                            }
                        }
                    }]
                }
            else:
                logging_ext.error('get_google_db_places Exception in Load',
                                  exc_info=True)
                return None
Example #10
0
 def post(self):
   try:
     if not check_good_server_version(self.request):
       self.response.out.write("BAD VERSION")
       return
     it = update_item_internal(self, self.user_id)
     logging.info('newOrUpdateItem %s by %s'%(it.place_name, self.user_id))
     ndb_models.mark_place_as_updated(str(it.key.id()),str(self.user_id))
     vote = Vote.query(Vote.voter == self.user_id, Vote.item == it.key).get()
     res = {'place':it.get_json(),
            'vote': vote.to_json()}
     json.dump(res, self.response.out)
   except:
     logging_ext.error('newOrUpdateItem', exc_info=True)
Example #11
0
def mark_place_as_updated(place_id_str, user_id_str):
    """
  :param place_id_str: string urlsafe
  :param user_id_str: string urlsafe
  :return:
  """
    try:
        taskqueue.add(url='/api/UpdatePlace',
                      params={
                          'placeId': place_id_str,
                          'userId': user_id_str
                      })
    except:
        logging_ext.error('** mark_place_as_updated', exc_info=True)
Example #12
0
 def post(self):
   if not check_good_server_version(self.request):
       self.response.out.write("BAD VERSION")
       return
   id = self.request.get('key')
   it = ndb.Key(Item, int(id)).get()
   if it:
     update_votes(it, self, self.user_id)
     # mark user as dirty
     self.response.out.write('OK')
     logging.debug("UpdateVote OK")
     return
   logging_ext.error("UpdateVote 404 for %s"%id)
   self.abort(404)
Example #13
0
    def handle_verification(cls, handler, user_id,signup_token,verification_type,invite_token):
        # it should be something more concise like
        # self.auth.get_user_by_token(user_id, signup_token)
        # unfortunately the auth interface does not (yet) allow to manipulate
        # signup tokens concisely
        user, ts = handler.user_model.get_by_auth_token(int(user_id), signup_token,
                                                     'signup')

        if not user:
            logging.info(
              'Could not find any userId with id "%s" signup token "%s"',
              user_id,
              signup_token)
            handler.display_message("Not found - if you've already followed this link there is no need to do it again")
            return

        # store userId data in the session
        handler.auth.set_session(handler.auth.store.user_to_dict(user), remember=True)

        if verification_type == 'v':
            # remove signup token,
            # we don't want users to come back with an old link
            handler.user_model.delete_signup_token(handler.user_id, signup_token)

            if not user.verified:
                user.verified = True
                user.put()
            try:
              if invite_token and invite_token != 'none':
                inv = Invite.checkInviteToken(invite_token)
                Friends.addFriends(inv, handler.user_id)
                Invite.delInviteToken(invite_token)
                logging.info("passwordVerificationHandler complete "+user.email_address)
            except:
              logging_ext.error(
                "Failed to add friend: passwordVerificationHandler GET",
                exc_info=True)
            handler.render_template('signup-complete.html')
        elif verification_type == 'p':
            # supply userId to the page
            params = {
                'userId': user,
                'token': signup_token
            }
            handler.render_template('resetpassword.html', params)
        else:
            logging.info('verification type not supported')
            handler.abort(404)
Example #14
0
 def get(self, key):
   try:
     photo = ndb.Key(urlsafe=key).get()
     if photo:
       self.response.headers['Content-Type'] = 'image/png'
       self.response.out.write(photo.get_thumb())
     else:
       default_thumb = memcache.get('DEFAULT-THUMB')
       if not default_thumb:
         default_thumb = Image()
         default_thumb.resize(65,55)
         self.response.headers['Content-Type'] = 'image/png'
         self.response.out.write(default_thumb)
         memcache.set('DEFAULT-THUMB', default_thumb)
   except Exception:
     logging_ext.error('ThumbHandler '+key, exc_info=True)
Example #15
0
def mark_vote_as_updated(vote_id_str, user_id_str):
    """
  :param vote_id_str: string urlsafe
  :param user_id_str: string urlsafe
  :return:
  """
    try:
        now_str = datetime.now().strftime(views.config['DATETIME_FORMAT'])
        taskqueue.add(url='/api/UpdateVote',
                      params={
                          'voteId': vote_id_str,
                          'userId': user_id_str,
                          'time': now_str
                      })
    except:
        logging_ext.error('** mark_vote_as_updated', exc_info=True)
Example #16
0
def get_updated_places_for_user(user_id_str, since):
    """
  get the list of change records for a given user
  :param user_id_str: string urlsafe
  :param since: datetime
  :return: query object on PlaceChange
  """
    try:
        result = Change.\
          query(
            Change.kind == Change.CHANGE_PLACE,
            Change.subscriberId==user_id_str,
            Change.when > since)
        return result
    except:
        logging_ext.error('** get_updated_places_for_user', exc_info=True)
Example #17
0
 def delete_item(handler, id):
   """
   deletes the votes for an item
   :param handler: RequestHandler
   :param id: int
   :return:
   """
   try:
     item = Item.get_by_id(int(id))
     if item:
       my_votes = Vote.query(Vote.voter == handler.user_id, Vote.item == item.key)
       for vote in my_votes:
         logging.info("deleteItem: " + str(vote.key))
         vote.key.delete()
     handler.response.write('OK')
   except Exception:
     logging_ext.error("delete_item", exc_info=True)
     handler.abort(500)
Example #18
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)
Example #19
0
    def post(self):  # should run at most 1/s due to entity group limit
        """
    Deletes all records of updated votes & places for the given user more than
    n days old

    """
        try:
            since = datetime.now() - timedelta(
                days=settings.config['updates_max_age'])
            # @ndb.transactional
            old_votes = Change.\
              query(Change.kind==Change.CHANGE_VOTE, Change.when < since).\
              fetch(keys_only=True)
            ndb.delete_multi(old_votes)
            old_places = Change.\
              query(Change.kind==Change.CHANGE_VOTE, Change.when < since).\
              fetch(keys_only=True)
            ndb.delete_multi(old_places)
            logging.info("ClearUserChangesWorker")
        except:
            logging_ext.error('** ClearUserChangesWorker', exc_info=True)
Example #20
0
 def get(self):
     try:
         logging.debug('getStrangerPlaces')
         lat = float(self.request.get("lat"))
         lng = float(self.request.get("lng"))
         place_names = []
         results = geo.findDbPlacesNearLoc(geo.LatLng(lat=lat, lng=lng),
                                           place_names=place_names)
         if results:
             results['search'] = {'lat': lat, 'lng': lng}
             # check_for_dirty_data(self, results)
             json.dump(results,
                       self.response.out,
                       default=views.json_serial)
         else:
             # logging.info("get_google_db_places near [%f,%f]: %s" %
             # (lat, lng, "none found"))
             logging.debug("getStrangerPlaces - none found ")
             self.error(401)
     except Exception:
         logging_ext.error("getStrangerPlaces", True)
Example #21
0
  def get(self):
    con = {"email": Category.query()}
    tok_list = ",".join(self.request.GET)
    logging_ext.info('FbRedirect: Params '+tok_list)
    try:
      # get the token
      token = self.request.params["access_token"]

      # is the email a user?
      # email not known

      # check if token is registered for user
      # if not, store it
      # log the user
      logging.info('FbRedirect: Logged in')
      con['message'] = "Logged in using facebook"
      self.render_template("oauth-fb.html", con)
    except:
      logging_ext.error("Unable to read data", exc_info=True)
      con['message'] = "Unable to read data"
      self.render_template("oauth-fb.html", con)
Example #22
0
 def getFullUserRecord(self, user, now=None):
     try:
         places_id2json = {}
         vote_list = []
         if settings.config['all_are_friends']:
             q = User.gql('')
         else:
             # start with me
             q = [user]
             # then get my friends
             for f in user.get_friends_key_list():
                 q.append(f.get())
         place_json = None
         place_id = None
         for u in q:
             if u:
                 user_votes = models.Vote.query(
                     models.Vote.voter == u.key.integer_id()).fetch()
                 for vote in user_votes:
                     try:
                         place_id = vote.item.id()
                         vote_list.append(vote.get_json())
                         if not place_id in places_id2json:
                             place_json = models.Item.id_to_json(place_id)
                             if "cuisineName" in place_json:
                                 places_id2json[place_id] = place_json
                     except Exception, e:
                         if place_json:
                             logging_ext.error(
                                 "** getFullUserRecord Exception 1 %s" %
                                 place_json['place_name'],
                                 exc_info=True)
                         else:
                             logging_ext.error(
                                 "** getFullUserRecord Exception %s" %
                                 place_id,
                                 exc_info=True)
         return vote_list, places_id2json
Example #23
0
 def post(self):
   #https://cloud.google.com/appengine/docs/python/
   # appidentity/#Python_Asserting_identity_to_other_App_Engine_apps
   logging.debug("UpdateItemFromAnotherAppAPI")
   #TODO: Security
   #if app_identity.get_application_id() != settings.API_TARGET_APP_ID:
   #  logging.debug("UpdateItemFromAnotherAppAPI 403: %s != %s"%\
   # (app_identity.get_application_id(),settings.API_TARGET_APP_ID))
   #  self.abort(403)
   #app_id = self.request.headers.get('X-Appengine-Inbound-Appid', None)
   #logging.info('UpdateItemFromAnotherAppAPI: from app %s'%app_id)
   #if app_id in settings.ALLOWED_APP_IDS:
   if True:
     seed_user = None
     for u in User.query():
       if 'pegah' in u.auth_ids:
         seed_user = u.key.id()
         break
     if seed_user:
       logging.debug("UpdateItemFromAnotherAppAPI user:"******""
       for k in self.request.params:
         params += '"%s": "%s"'%(k, self.request.params[k])
       logging.debug("UpdateItemFromAnotherAppAPI params: "+params)
       if update_item_internal(self, seed_user, allow_update=False):
         logging.debug("UpdateItemFromAnotherAppAPI Done ")
       else:
         logging.debug("UpdateItemFromAnotherAppAPI Existed ")
       self.response.out.write("OK")
     else:
       logging_ext.error("UpdateItemFromAnotherAppAPI - couldn't get seed user",
                     exc_info=True)
       self.abort(500)
   else:
     logging.debug("UpdateItemFromAnotherAppAPI not allowed")
     self.abort(403)
Example #24
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)
Example #25
0
                        'cuisineName': "",
                        'telephone': '',
                        'img': '',
                        'edited': 0,
                        'thumbnail': '',
                        'up': 0,
                        'down': 0,
                        'owner': None,
                        # is_map is True if the point came
                        # from a google places API search. Default False
                        'is_map': True
                    }
                    addresses.append(detail)
                    results["item_count"] += 1
                results['items'] = addresses
                return results
            except Exception, e:
                logging_ext.error('get_google_db_places Exception processing',
                                  exc_info=True)
                return results
        elif addressResult['status'] == "ZERO_RESULTS":
            logging.info("get_google_db_places near [%f,%f]: %s - %s" %
                         (lat, lng, name, addressResult['status']),
                         exc_info=True)
            return results
        else:
            logging_ext.error("get_google_db_places near [%f,%f]: %s" %
                              (lat, lng, addressResult['status']),
                              exc_info=True)
            return results
Example #26
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=views.json_serial)
            return

        if my_id:
            try:
                # logged in
                #check if the client version is allowed
                good_version = False
                if 'version' in self.request.params:
                    version = float(self.request.params['version'])
                    min_version = Config.min_server_version_allowed()
                    if version >= float(min_version):
                        good_version = True
                if not good_version:
                    logging_ext.error(
                        "getUserRecordFastViaWorkers BAD VERSION")
                    self.response.out.write("BAD_VERSION")
                    return

                #good client version if we got here
                result = {
                    "id": my_id,
                    "admin": self.user.profile().is_admin,
                    "version": settings.config["version"],
                    "min_version": settings.config['min_version']
                }
                since = None
                now = datetime.now()
                if 'since' in self.request.params:
                    try:
                        # move since back in time to allow for error
                        since = datetime.strptime(
                          self.request.params['since'],
                          views.config['DATETIME_FORMAT']) - \
                                views.config['TIMING_DELTA']
                        vote_list, place_id2json = self.getIncrement(
                            my_id, since)
                    except OverflowError, ex:
                        logging_ext.error(
                            "** getFullUserRecord Time error with %s" % since,
                            exc_info=True)
                        #full update
                        vote_list, place_id2json = self.getFullUserRecord(
                            self.user)
                else:
                    #full update
                    vote_list, place_id2json = self.getFullUserRecord(
                        self.user)

                friends_list = []
                if views.config['all_are_friends']:
                    q = User.gql('')
                    for u in q:
                        user_str = {
                            "id": u.get_id(),
                            # todo is it first_name?
                            'name': u.screen_name
                        }
                        friends_list.append(user_str)
                else:
                    friends = self.user.get_friends_key_list()
                    for f in friends:
                        friend = f.get()
                        try:
                            user_str = {
                                "id": f.id(),
                                # todo is it first_name?
                                'name': friend.screen_name
                            }
                        except:
                            logging.error("getFullUserRecord Friends error")
                        friends_list.append(user_str)

                sentInvites = models.InviteInternal.query(
                    models.InviteInternal.inviter == my_id)
                recdInvites = models.InviteInternal.query(
                    models.InviteInternal.invitee == my_id)
                sent = []
                for i in sentInvites:
                    sent.append(i.to_json())
                recd = []
                for i in recdInvites:
                    recd.append(i.to_json())
                result["sentInvites"] = sent
                result["receivedInvites"] = recd
                result['votes'] = vote_list
                result["places"] = place_id2json
                result["friendsData"] = friends_list
                json_str = json.dumps(result, default=views.json_serial)
                try:
                    since_str = str(since) if since else ""
                    logging.debug(
                        "GetFullUserRecord for %s %s P:%d, V:%d, F:%d" %
                        (self.user.screen_name, since_str, len(place_id2json),
                         len(vote_list), len(friends_list)))
                except:
                    pass
                try:
                    #logging
                    logging.debug("getUserRecordFastViaWorkers done ")
                except:
                    pass
                self.response.out.write(json_str)
                #profile_out("getFullUserRecord")
                return
Example #27
0
def update_item_internal(self, user_id, allow_update=True):
  def update_field(field_name, value):
    # so we can log edits
    old_val = getProp(it,field_name)
    if old_val != value:
      setattr(it,field_name,value)
      changed[field_name]="%s->%s"%(old_val,value)

  # is it an edit or a new?
  it = Item.get_unique_place(self.request, allow_update)
  if not it:
    # it will be None if it exists and not allow_update
    return None
  img = update_photo(it, self)
  # it.place_name = self.request.get('new-title') set in get_unique_place
  changed = {}
  update_field ('address', self.request.get('address'))
  it.owner = user_id
  if img:
    it.photo = img
  else:
    if not it.photo or not it.website:
        #TODO: make this async: load one from google
      detail = geo.getPlaceDetailFromGoogle(it)
      if not it.photo:
        img = DBImage()
        remoteURL = detail['photo']
        if remoteURL:
          thumb_url=None
          try:
            main_url = remoteURL % 250
            data = urllib2.urlopen(main_url)
            img.picture = db.Blob(data.read())
            img.remoteURL = None
            thumb_url = remoteURL % 65
            thumb_data = urllib2.urlopen(thumb_url)
            img.thumb = db.Blob(thumb_data.read())
            img.put()
            it.photo = img.key
          except:
            if thumb_url:
              logging_ext.error("update_item_internal: remote url ["+str(thumb_url)+"] Exception", exc_info=True)
            else:
              logging_ext.error("update_item_internal: remote url Exception", exc_info=True)
            it.photo = None
      if 'telephone' in detail and detail['telephone'] != None:
        it.telephone = detail['telephone']
      if 'website' in detail and detail['website']:
        it.website = detail['website']

  if not it.telephone:
    it.telephone = self.request.get('telephone')
  if not it.website:
    it.website = self.request.get('website')

  # category
  posted_cat = self.request.get("cuisine")
  try:
    cat_key = ndb.Key(Category,posted_cat)
  except:
    cat_key = None
  update_field('category', cat_key)
  if "place_name" in self.request.params:
    update_field('place_name', self.request.params['place_name'])
  it.put() # so the key is set
  # refresh cache
  update_votes(it, self, user_id)
  # todo: why?
  logging.info("update_item_internal for "+it.place_name+": "+str(changed))
  return it
Example #28
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)
Example #29
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)
Example #30
0
                                         Change.subscriberId == str(my_id),
                                         Change.when > since)
            for uv in updated_votes:
                key = ndb.Key('Vote', int(uv.voteId))
                v = key.get()
                if v:
                    try:
                        vote_list.append(v.json)
                        place_id = v.item.id()
                        if not place_id in places_id2json:
                            places_id2json[place_id] = v.item.get().get_json()
                    except Exception, E:
                        pass
            return vote_list, places_id2json
        except:
            logging_ext.error('** getIncrement', exc_info=True)

    def getFullUserRecord(self, user, now=None):
        try:
            places_id2json = {}
            vote_list = []
            if settings.config['all_are_friends']:
                q = User.gql('')
            else:
                # start with me
                q = [user]
                # then get my friends
                for f in user.get_friends_key_list():
                    q.append(f.get())
            place_json = None
            place_id = None