Exemplo n.º 1
0
    def test_importer_values(self):
        try:
            importer = ExternalEventImporter(self.directory)

            string_values = [
                'title', 'short_description', 'long_description', 'locality',
                'street', 'housenumber', 'zipcode', 'town', 'location_url',
                'event_url', 'organizer', 'contact_name', 'contact_email',
                'contact_phone', 'prices', 'registration', 'source_id',
                'fetch_id'
            ]
            now = default_now().replace(microsecond=0)
            then = now + timedelta(days=10)

            event = {s: s for s in string_values}

            event['last_update'] = now
            event['start'] = then
            event['end'] = then + timedelta(hours=1)
            event['timezone'] = default_timezone()
            event['whole_day'] = False
            event['recurrence'] = 'RRULE:FREQ=DAILY;COUNT=2'

            event['cat1'] = set(['c1', 'c2'])
            event['cat2'] = set(['c3', 'c4'])

            event['longitude'] = 7.8673189
            event['latitude'] = 46.6859853

            # :TODO: test image and attachement download
            # event['image'] =
            # event['attachment_1'] =
            # event['attachment_2'] =

            imports, deleted = importer.fetch_one('source', lambda: [event])
            imported = self.catalog.query()
            self.assertEquals(imports, 1)
            self.assertEquals(len(imported), 1)

            imported = imported[0].getObject()
            for s in string_values:
                self.assertTrue(s in vars(imported))
                self.assertTrue(vars(imported)[s] == s)

            self.assertEquals(imported.start, now + timedelta(days=10))
            self.assertEquals(imported.end, now + timedelta(days=10, hours=1))
            self.assertEquals(imported.recurrence, 'RRULE:FREQ=DAILY;COUNT=2')
            self.assertFalse(imported.whole_day)

            self.assertTrue('c1' in imported.cat1)
            self.assertTrue('c2' in imported.cat1)
            self.assertTrue('c3' in imported.cat2)
            self.assertTrue('c4' in imported.cat2)

            self.assertEquals(
                IGeoreferenced(imported).coordinates, [7.8673189, 46.6859853])

        finally:
            # Clean up (transaction has been commited)
            self.cleanup_after_fetch_one()
Exemplo n.º 2
0
    def __call__(self):
        """Request parameters are 'type' and 'coordinates'."""
        request = self.request
        response = request.response
        try:
            gtype = request.form.get('type')
            coords = request.form.get('coordinates')
            data = '{"type": "%s", "coordinates": %s}' % (gtype, coords)
            obj = geojson.loads(data, object_hook=geojson.GeoJSON.to_instance)
        except:
            raise
            response.setStatus(400)
            return "Input geometry is not acceptable"

        # Input is 900913, transform back to lon/lat
        result = self.transform(obj, inverse=True)
        g = IGeoreferenced(self.context)
        g.setGeoInterface(result.type, result.coordinates)
        notify(ObjectGeoreferencedEvent(g))

        if request.get('HTTP_REFERER'):
            response.redirect(
                request.get('HTTP_REFERER').split('?')[0] +
                '?portal_status_message=Changes%20saved.')
        else:
            response.setStatus(200)
            return "Geometry edited successfully"
Exemplo n.º 3
0
 def reprExtent(self):
     try:
         g = IGeoreferenced(self.context)
         points = list(explode(g.coordinates))
         return hull(points), g.precision
     except:
         return None, "unlocated"
Exemplo n.º 4
0
 def coordinates(self):
     if self.has_map:
         geo_obj = IGeoreferenced(self.context)
         if getattr(geo_obj, 'coordinates', False):
             return geo_obj.type, geo_obj.coordinates
         else:
             return None, None
     return None, None
Exemplo n.º 5
0
    def __init__(self, context, request):
        self.context = context
        self.request = request

        try:
            self.geom = IGeoreferenced(self.context)
        except:
            self.geom = NullGeometry()
        self.styles = get_feature_styles(context)
Exemplo n.º 6
0
 def __init__(self, context):
     """Initialize adapter."""
     self.context = context
     self._adapter = None
     x = list(self.context.getLocations())
     if len(x) == 0:
         raise ValueError("Unlocated: could not adapt %s" % str(context))
     else:
         self._adapter = IGeoreferenced(x[0])
 def wkt(self):
     try:
         from shapely.geometry.geo import asShape
     except ImportError:
         from pygeoif.geometry import as_shape as asShape
     try:
         return asShape(IGeoreferenced(self.context).geo).wkt
     except (ValueError, TypeError, NotImplementedError):
         # context is not a valid shape.
         pass
     return u''
Exemplo n.º 8
0
 def distance(self, b):
     try:
         g = IGeoreferenced(self.context)
         geom = asShape({'type': g.type, 'coordinates': g.coordinates})
         y0 = geom.centroid.y
         other = asShape(b.zgeo_geometry)
         d = geom.distance(other)
         return int(math.cos(math.pi*y0/180.0)*d/F/1000)
     except:
         log.warn("Failed to find distance between %s and %s" % (
             self.context, b.getPath()))
         raise
Exemplo n.º 9
0
 def __init__(self, context):
     """Initialize adapter."""
     self.context = context
     self.geo = None
     x = []
     place = self.context.aq_parent
     for o in filter(lambda x: temporal_overlap(self.context, x),
                     place.getLocations()):
         try:
             x.append(IGeoreferenced(o))
         except ValueError:
             continue
     if len(x) > 0:
         self.geo = self._geo(x)
     else:
         geo_parts = []
         for ob in self.context.getFeatures():
             geo_parts.append(IGeoreferenced(ob))
         if geo_parts:
             self.geo = self._geo(geo_parts)
     if self.geo is None:
         raise NotLocatedError("Location cannot be determined")
Exemplo n.º 10
0
 def coordinates(self):
     geo_adapter = queryAdapter(self.context, IGeoreferenced)
     if geo_adapter:
         try:
             from shapely.geometry.geo import asShape
         except ImportError:
             from pygeoif.geometry import as_shape as asShape
         try:
             return asShape(IGeoreferenced(self.context).geo).wkt
         except (ValueError, TypeError, NotImplementedError):
             # context is not a valid shape.
             # create a validator?
             pass
     return u''
Exemplo n.º 11
0
 def __init__(self, context):
     """Initialize adapter."""
     self.context = context
     self.geo = None
     x = []
     for o in self.context.getLocations():
         try:
             x.append(IGeoreferenced(o))
         except ValueError:
             continue
     if len(x) > 0:
         precise = [xx for xx in x if xx.precision == 'precise']
         if len(precise) >= 1:
             x = precise
         self.geo = self._geo(x)
     else:
         geo_parts = []
         for ob in self.context.getFeatures():
             geo_parts.append(IGeoreferenced(ob))
         if geo_parts:
             self.geo = self._geo(geo_parts)
     if self.geo is None:
         raise NotLocatedError("Location cannot be determined")
Exemplo n.º 12
0
    def test_override_geo_with_related_contact(self):
        add_behavior(
            'Event',
            'cpskin.agenda.behaviors.related_contacts.IRelatedContacts'
        )  # noqa
        add_behavior('Event', ICoordinates.__identifier__)
        event = api.content.create(container=self.portal,
                                   type='Event',
                                   id='myevent')

        # add some contacts
        applyProfile(self.portal, 'collective.contact.core:default')
        add_behavior('organization', ICoordinates.__identifier__)
        directory = api.content.create(container=self.portal,
                                       type='directory',
                                       id='directory')
        organization = api.content.create(container=directory,
                                          type='organization',
                                          id='organization')
        organization.title = u'IMIO'
        organization.street = u'Rue Léon Morel'
        organization.number = u'1'
        organization.zip_code = u'5032'
        organization.city = u'Isnes'

        # set related contact
        intids = getUtility(IIntIds)
        to_id = intids.getId(organization)
        rv = RelationValue(to_id)
        event.location = rv
        notify(ObjectModifiedEvent(event))

        # coord = ICoordinates(event)
        view = getMultiAdapter((event, event.REQUEST), name='geoview')
        coord = view.getCoordinates()
        self.assertEqual(coord, (None, None))
        coordinates = ICoordinates(event).coordinates

        self.assertEqual(coordinates, u'')

        # check if event georeferenced is correct
        orga_geo = IGeoreferenced(organization)
        orga_geo.setGeoInterface('Point', (4.711178, 50.504827))
        notify(ObjectModifiedEvent(event))
        view = getMultiAdapter((event, event.REQUEST), name='geoview')
        coord = view.getCoordinates()
        self.assertEqual(coord, ('Point', (4.711178, 50.504827)))
        coordinates = ICoordinates(event).coordinates
        self.assertEqual(coordinates, 'POINT (4.711178 50.504827)')
Exemplo n.º 13
0
def zgeo_geometry_value(obj):
    if isinstance(obj.location, RelationValue):
        if obj.location.isBroken():
            obj.location = None
            raise AttributeError
        contact_obj = obj.location.to_object
    else:
        contact_obj = obj
    if IGeoreferenceable.providedBy(contact_obj):
        # old_geo = IGeoreferenced(obj)
        # old_geo.removeGeoInterface()
        geo = IGeoreferenced(contact_obj)
        if geo.type and geo.coordinates:
            return {'type': geo.type, 'coordinates': geo.coordinates}
    # The catalog expects AttributeErrors when a value can't be found
    raise AttributeError
Exemplo n.º 14
0
 def __init__(self, context):
     self.context = context
     try:
         g = IGeoreferenced(context)
         self.precision = g.precision
         if not g.coordinates:
             raise NotLocatedError("Adapter has no coordinates")
         if g.type == 'Point':
             self.coords = tuple(g.coordinates)
         else:
             self.coords = tuple(
                 asShape({
                     'type': g.type,
                     'coordinates': g.coordinates
                 }).centroid.coords)[0]
     except (ValueError, NotLocatedError):
         self.precision = "unlocated"
         self.coords = None
Exemplo n.º 15
0
    def test_save_zgeo_catalog_from_contact(self):
        applyProfile(self.portal, 'collective.geo.leaflet:default')
        add_behavior('Event', IRelatedContacts.__identifier__)
        add_behavior('Event', ICoordinates.__identifier__)
        event = api.content.create(container=self.portal,
                                   type='Event',
                                   id='myevent')

        # add some contacts
        applyProfile(self.portal, 'collective.contact.core:default')
        add_behavior('organization', ICoordinates.__identifier__)
        directory = api.content.create(container=self.portal,
                                       type='directory',
                                       id='directory')
        organization = api.content.create(container=directory,
                                          type='organization',
                                          id='organization')
        organization.title = u'IMIO'
        organization.street = u'Rue Léon Morel'
        organization.number = u'1'
        organization.zip_code = u'5032'
        organization.city = u'Isnes'

        # set related contact
        intids = getUtility(IIntIds)
        to_id = intids.getId(organization)
        rv = RelationValue(to_id)
        event.location = rv
        notify(ObjectModifiedEvent(event))
        event.reindexObject()
        # geo = IGeoreferenced(event)
        brain = api.content.find(UID=event.UID())[0]
        # brain.zgeo_geometry
        import Missing
        self.assertTrue(brain.zgeo_geometry == Missing.Value)
        orga_geo = IGeoreferenced(organization)
        orga_geo.setGeoInterface('Point', (4.711178, 50.504827))
        notify(ObjectModifiedEvent(event))
        brain = api.content.find(UID=event.UID())[0]
        self.assertEqual(brain.zgeo_geometry['type'], 'Point')
Exemplo n.º 16
0
    def nearest(self):
        catalog = getToolByName(self.context, 'portal_catalog')

        class NeighborBrain(AbstractCatalogBrain, NoBrainer):
            pass

        cschema = catalog._catalog.schema
        scopy = cschema.copy()
        scopy['data_record_id_'] = len(cschema.keys())
        scopy['data_record_score_'] = len(cschema.keys())+1
        scopy['data_record_normalized_score_'] = len(cschema.keys())+2
        scopy['distance'] = len(cschema.keys())+3
        scopy['center'] = len(cschema.keys())+4
        NeighborBrain.__record_schema__ = scopy
        try:
            g = IGeoreferenced(self.context)
        except:
            return []

        def gen():
            for brain in catalog(
                    geolocation={'query': (g.bounds, 10), 'range': 'nearest'},
                    portal_type={'query': ['Place']},
                    sort_index='geolocation',
                    ):
                if brain.getId == self.context.getId():
                    # skip self
                    continue
                neighbor = NeighborBrain().__of__(catalog)
                for k in brain.__record_schema__.keys():
                    neighbor[k] = brain[k]
                neighbor['distance'] = self.distance(brain)
                neighbor['center'] = self.center(brain)
                yield neighbor

        b_size = 20
        b_start = self.request.get('b_start', 0)
        batch = Batch(list(gen()), b_size, int(b_start), orphan=0)
        return batch
Exemplo n.º 17
0
    def __call__(self):
        response = self.request.response
        geo = IGeoreferenced(self.context)
        where = self.transform(geo)
        if geo.type == 'Point':
            centroid = where
        else:
            shape = asShape(geo)
            centroid = self.transform(shape.centroid)
        context_url = self.context.absolute_url()
        response.setHeader('Content-Type', 'text/javascript')
        return """
// Javascript summary of a Pleiades entity
var url_marker_gold = "%s/++resource++marker_gold.png";
var url_marker_shadow = "%s/++resource++marker_shadow.png";
var pleiades_oljs = %s;
        """ % (context_url, context_url,
               geojson.dumps({
                   'uid': self.context.UID(),
                   'where': where,
                   'centroid': centroid,
               }))
Exemplo n.º 18
0
 def has_mapdata(self, item):
     try:
         return IGeoreferenced(item).type is not None
     except TypeError:
         return False
 def getCoordinates(self):
     if (self.isGeoreferenceable()):
         geo = IGeoreferenced(self.context)
         return geo.type, geo.coordinates
     else:
         return None, None
Exemplo n.º 20
0
def isPrecise(o):
    try:
        return (ILocation.providedBy(o) and o._getGeometryRaw()
                and IGeoreferenced(o))
    except (ValueError, NotLocatedError):
        return False
Exemplo n.º 21
0
 def has_mapdata(self):
     return IGeoreferenced(self).type is not None
Exemplo n.º 22
0
 def coordinates(self):
     return IGeoreferenced(self.context)
Exemplo n.º 23
0
def render_json_response(request, items, compact):
    request.response.setHeader("Content-Type", "application/json")
    request.response.setHeader("Access-Control-Allow-Origin", "*")  # CORS

    utc = pytz.timezone('utc')
    duplicates = set()

    result = []
    for idx, item in enumerate(items):
        if compact:
            if item.id in duplicates:
                continue
            duplicates.add(item.id)

        event = {}

        start = item.start
        end = item.end

        if not start.tzinfo:
            start = utc.localize(start)
        if not end.tzinfo:
            end = utc.localize(end)

        updated = item.modification_date.asdatetime().replace(microsecond=0)
        event['last_update'] = updated.isoformat()
        event['id'] = item.id
        event['url'] = item.url()
        event['title'] = item.title
        event['short_description'] = item.short_description
        event['long_description'] = item.long_description
        event['cat1'] = item.cat1
        event['cat2'] = item.cat2
        event['start'] = utc.normalize(start).isoformat()
        event['end'] = utc.normalize(end).isoformat()
        event['recurrence'] = item.recurrence if compact else ''
        event['whole_day'] = item.whole_day
        event['timezone'] = item.timezone
        event['locality'] = item.locality
        event['street'] = item.street
        event['housenumber'] = item.housenumber
        event['zipcode'] = item.zipcode
        event['town'] = item.town
        event['location_url'] = item.location_url
        event['organizer'] = item.organizer
        event['contact_name'] = item.contact_name
        event['contact_email'] = item.contact_email
        event['contact_phone'] = item.contact_phone
        event['prices'] = item.prices
        event['event_url'] = item.event_url
        event['registration'] = item.registration
        event['submitter'] = item.submitter
        event['submitter_email'] = item.submitter_email

        event['images'] = []
        if isinstance(item.image, NamedFile):
            image = {}
            image['name'] = item.image.filename
            image['url'] = item.absolute_url() + '/@@images/image'
            event['images'].append(image)

        event['attachements'] = []
        if isinstance(item.attachment_1, NamedFile):
            attachement = {}
            attachement['name'] = item.attachment_1.filename
            attachement['url'] = item.absolute_url()
            attachement['url'] += '/@@download/attachment_1'
            event['attachements'].append(attachement)
        if isinstance(item.attachment_2, NamedFile):
            attachement = {}
            attachement['name'] = item.attachment_2.filename
            attachement['url'] = item.absolute_url()
            attachement['url'] += '/@@download/attachment_2'
            event['attachements'].append(attachement)

        event['longitude'] = None
        event['latitude'] = None
        try:
            geo = IGeoreferenced(item)
            if geo.type == 'Point':
                event['longitude'] = geo.coordinates[0]
                event['latitude'] = geo.coordinates[1]
        except TypeError:
            pass

        result.append(event)

    return json.dumps(result)