Пример #1
0
    def get(self):
        login_user = get_login_user()

        format = self.request.get("format", "JSON")

        if format not in ['JSON','yaml']:
            logging.Critical("Unknown format for export: %s" % (format))
            self.error(500)
            return

        # not logged in
        if not login_user:
            self.redirect('/login')
            return

        if self.request.get('attic',"") == 'True':
            attic = True
        else:
            attic = False

        # shall a specific dataset be exported?
        key = self.request.get("key", None)


        logging.info("export format:  attic: %d user: %s admin: %d" % (attic,user.nickname(),users.is_current_user_admin()))
        self.response.headers['Content-Type'] = 'text/plain'

        # Administrator exports everything
        contacts = []
        if users.is_current_user_admin():
            if key:
                con = Contact.get(key)
                if con:
                    contacts.append(encode_contact(con, include_attic=attic, signed_in=True, is_admin=True))
            else:
                q_con = Contact.all()
                for con in q_con:
                    contacts.append(encode_contact(con, include_attic=attic, signed_in=True, is_admin=True))
        else:
            login_user = get_login_user(user)
            if key:
                con = Contact.get(key)
                if con:
                    contacts.append(encode_contact(con, include_attic=attic, signed_in=True, is_admin=True))
            else:
                # export everything this user can see
                for ckey in visible_contacts(login_user, include_attic=attic):
                    con = Contact.get(ckey)
                    contacts.append(encode_contact(con, include_attic=attic, me=login_user.me))

        self.response.headers['Content-Disposition'] = "attachment; filename=address_export.json"
        if format == 'JSON':
            self.response.headers['Content-Type'] = "text/plain"
            self.response.out.write(json.dumps(contacts,indent=2))
        else:
            self.response.headers['Content-Type'] = "text/yaml"
            self.response.out.write(yaml.dump(contacts,))
Пример #2
0
    def get(self):
        login_user = get_login_user()
        # must be logged in to submit position
        if not login_user:
            self.error(500)
            return

        lat = self.request.get("lat", None)
        lon = self.request.get("lon", None)
        place = self.request.get("place", None)
        user = self.request.get("user", None)
        # PERMISSION_DENIED (1)
        # POSITION_UNAVAILABLE (2)
        # TIMEOUT (3)
        # UNKNOWN_ERROR (0)
        # firefox supports only (1) in case of a permanent denial
        err = self.request.get("err", None)
        logging.debug("LocationHandler.get() err: %s lat: %s lon: %s place: %s" % (err,lat,lon,place))

        if not err:
            login_user.location.lat = float(lat)
            login_user.location.lon = float(lon)
            login_user.place = place
            login_user.location_timestamp = datetime.now()
            # ask again in an hour
            login_user.ask_geolocation = datetime.now() + timedelta(hours=1)
            login_user.put()

        # response is always OK
        self.response.set_status(200)
        return
Пример #3
0
    def post(self):
        login_user = get_login_user()
        template_values = get_current_user_template_values(login_user,self.request.uri)

        format = self.request.get("json", None)
        if not format:
            format = 'yaml'
        else:
            format = 'JSON'

        # not logged in
        if not login_user:
            self.redirect('/login')
            return

        if memcache.get('import_status'):
            # there is already an import going on
            template_values['errors'] = ["Previous import is still processing. Please be patient..."]
            path = os.path.join(os.path.dirname(__file__), "take2import_file.html")
            self.response.out.write(template.render(path, template_values))
            return
        memcache.set('import_status', "Queued import task", time=30)
        memcache.set('import_data', self.request.get("backup"), time=300)

        logging.info("")

        # start background process
        taskqueue.add(url='/import_task', queue_name="import",
                      params={'login_user': str(login_user.key()), 'format': self.request.get("format", None)})

        # redirect to page which will show the import progress
        self.redirect('/import_status')
Пример #4
0
    def get(self):
        login_user = get_login_user()
        # bbox is in GeoJson notation [minlon,minlat,maxlon,maxlat]
        bbox = self.request.get('bbox',"0,0,0,0").split(',')
        minlat = float(bbox[1])
        minlon = float(bbox[0])
        maxlat = float(bbox[3])
        maxlon = float(bbox[2])

        geojson = {"type": "FeatureCollection"}
        geojson['features'] = []

        box = geo.geotypes.Box(maxlat,maxlon,minlat,minlon)
        for geoix in GeoIndex.bounding_box_fetch(GeoIndex.all(), box, max_results=111):
            try:
                con = geocode_contact(geoix.contact_ref, include_attic=False, login_user=login_user)
                if con:
                    # geoconding successful
                    geojson['features'].extend(con)
                else:
                    nongeo.append(encode_contact(contact_ref, login_user, include_attic=False))
            except db.ReferencePropertyResolveError:
                logging.critical("AttributeError while encoding")


        geojson["bbox"] = bbox

        logging.debug("Return %s objects" % (len(geojson['features'])))
        # encode and return
        # self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Content-Type'] = "text/plain"
        self.response.out.write(json.dumps(geojson))
Пример #5
0
    def get(self):
        login_user = get_login_user()
        template_values = get_current_user_template_values(login_user,self.request.uri)

        # not logged in
        if not login_user:
            self.redirect('/login')
            return

        path = os.path.join(os.path.dirname(__file__), "take2import_file.html")
        self.response.out.write(template.render(path, template_values))
Пример #6
0
    def get(self):
        login_user = get_login_user()
        template_values = get_current_user_template_values(login_user,self.request.uri)

        # not logged in. display login options
        if not login_user:
            path = os.path.join(os.path.dirname(__file__), 'take2login.html')
            self.response.out.write(template.render(path, template_values))
            return

        if not login_user.me:
            self.redirect('/welcome')
            return

        self.redirect('/')
        return
Пример #7
0
    def get(self):
        """processes the signup form"""
        authenticated_user = users.get_current_user()
        login_user = get_login_user()
        template_values = get_current_user_template_values(login_user,self.request.uri)

        # not logged in
        if not authenticated_user:
            self.redirect('/login')
            return

        # already connected
        if login_user and login_user.me:
            self.redirect('/')
            return

        template_values['errors'] = []

        person = PersonBean.edit(None,self.request)
        template_values.update(person.get_template_values())
        err = person.validate()
        terms=self.request.get("terms", None)
        if not terms:
            err.append("You must also acknowledge the terms and conditions.")

        if not err:
            try:
                db.run_in_transaction(initial_user_setup, authenticated_user, person)
            except:
                # an error occured in storing the data
                logging.exception('Transaction failed while storing LoginUser and Person')
                template_values['errors'].append('Database error. Sorry.')
        else:
            template_values['errors'].extend(err)

        if len(template_values['errors']):
            path = os.path.join(os.path.dirname(__file__), "take2welcome.html")
            self.response.out.write(template.render(path, template_values))
            return

        # create search index which is usually done by the PersonBean but not here
        # because the index table is not in the entity group
        update_index(person.entity)

        self.redirect('/')
Пример #8
0
    def get(self):
        """processes the signup form"""
        authenticated_user = users.get_current_user()
        login_user = get_login_user()

        template_values = get_current_user_template_values(login_user,self.request.uri)

        # not logged in
        if not authenticated_user:
            self.redirect('/login')
            return

        # already connected
        if login_user and login_user.me:
            self.redirect('/')
            return

        # prepare list of days and months
        template_values.update(prepare_birthday_selectors())
        path = os.path.join(os.path.dirname(__file__), 'take2welcome.html')
        self.response.out.write(template.render(path, template_values))
        return
Пример #9
0
    def get(self):
        login_user = get_login_user()
        query = self.request.get('query',"")
        include_attic = True if self.request.get('attic',None) else False

        # data structures for data transport to client
        nongeo = []
        geojson = []
        geojson = {"type": "FeatureCollection"}
        geojson['features'] = []

        minlat = 0.0
        maxlat = 0.0
        minlon = 0.0
        maxlon = 0.0

        if query:
            cis = lookup_contacts(query, include_attic)
            # Save the query result in memcache together with the information about
            # which portion of it we are displaying (the first result_size datasets as
            # it is a fresh query!)
            if login_user:
                if not memcache.set('query', {'query': query, 'offset': 0, 'results': cis}, time=5000, namespace=str(login_user.key())):
                    logging.error("memcache failed")
            # fetch a number of data from the results
            for contact in db.get(cis[0:settings.RESULT_SIZE]):
                if not contact:
                    # may happen if index is not up to date
                    logging.warning("Query returned invalid contact reference")
                    continue
                try:
                    con = geocode_contact(contact, include_attic=include_attic, login_user=login_user)
                    if con:
                        # geoconding successful
                        geojson['features'].extend(con)
                    else:
                        nongeo.append(encode_contact(contact_ref, login_user, include_attic=False))
                except db.ReferencePropertyResolveError:
                    logging.critical("AttributeError while encoding")


        # calculate bounding box (viewport)
        for feature in geojson['features']:
            coords = feature['geometry']['coordinates']
            if feature['id'] == 'display':
                # initialize to first point
                if minlon == 0.0:
                    minlon = coords[0]
                    maxlon = coords[0]
                if coords[0] > maxlon:
                    maxlon = coords[0]
                if coords[0] < minlon:
                    minlon = coords[0]
                if minlat == 0.0:
                    minlat = coords[1]
                    maxlat = coords[1]
                if coords[1] > maxlat:
                    maxlat = coords[1]
                if coords[1] < minlat:
                    minlat = coords[1]
        geojson["bbox"] = [minlon,minlat,maxlon,maxlat]

        # encode and return
        # self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Content-Type'] = "text/plain"
        self.response.out.write(json.dumps(geojson, indent= 2 if settings.DEBUG else 0))
Пример #10
0
    def get(self):
        login_user = get_login_user()
        template_values = get_current_user_template_values(login_user,self.request.uri)

        path = os.path.join(os.path.dirname(__file__), 'take2map.html')
        self.response.out.write(template.render(path, template_values))