Ejemplo n.º 1
0
def map_thumbnail(request, mapid):
    map_obj = _resolve_map(request, mapid)
    try:
        image = None
        try:
            image = _prepare_thumbnail_body_from_opts(
                request.body, request=request)
        except BaseException:
            image = _render_thumbnail(request.body)

        if not image:
            return HttpResponse(
                content=_('couldn\'t generate thumbnail'),
                status=500,
                content_type='text/plain'
            )
        filename = "map-%s-thumb.png" % map_obj.uuid
        map_obj.save_thumbnail(filename, image)

        return HttpResponse(_('Thumbnail saved'))
    except BaseException:
        return HttpResponse(
            content=_('error saving thumbnail'),
            status=500,
            content_type='text/plain'
        )
Ejemplo n.º 2
0
def map_thumbnail(request, mapid):
    map_obj = _resolve_map(request, mapid)
    try:
        image = None
        try:
            image = _prepare_thumbnail_body_from_opts(
                request.body, request=request)
        except BaseException:
            image = _render_thumbnail(request.body)

        if not image:
            return HttpResponse(
                content=_('couldn\'t generate thumbnail'),
                status=500,
                content_type='text/plain'
            )
        filename = "map-%s-thumb.png" % map_obj.uuid
        map_obj.save_thumbnail(filename, image)

        return HttpResponse(_('Thumbnail saved'))
    except BaseException:
        return HttpResponse(
            content=_('error saving thumbnail'),
            status=500,
            content_type='text/plain'
        )
Ejemplo n.º 3
0
def map_thumbnail(request, mapid):
    try:
        map_obj = _resolve_map(request, mapid)
    except PermissionDenied:
        return HttpResponse(_("Not allowed"), status=403)
    except Exception:
        raise Http404(_("Not found"))
    if not map_obj:
        raise Http404(_("Not found"))

    try:
        image = None
        try:
            image = _prepare_thumbnail_body_from_opts(
                request.body, request=request)
        except Exception:
            image = _render_thumbnail(request.body)

        if not image:
            return HttpResponse(
                content=_('couldn\'t generate thumbnail'),
                status=500,
                content_type='text/plain'
            )
        filename = "map-%s-thumb.png" % map_obj.uuid
        map_obj.save_thumbnail(filename, image)

        return HttpResponse(_('Thumbnail saved'))
    except Exception:
        return HttpResponse(
            content=_('error saving thumbnail'),
            status=500,
            content_type='text/plain'
        )
Ejemplo n.º 4
0
def map_thumbnail(request, mapid):
    if request.method == 'POST':
        map_obj = _resolve_map(request, mapid)
        try:
            image = None
            try:
                image = _prepare_thumbnail_body_from_opts(request.body)
            except BaseException:
                image = _render_thumbnail(request.body)

            if not image:
                return
            filename = "map-%s-thumb.png" % map_obj.uuid
            map_obj.save_thumbnail(filename, image)

            return HttpResponse('Thumbnail saved')
        except BaseException:
            return HttpResponse(content='error saving thumbnail',
                                status=500,
                                content_type='text/plain')
Ejemplo n.º 5
0
def create_thumbnail(instance, thumbnail_remote_url, thumbnail_create_url=None,
                     check_bbox=False, ogc_client=None, overwrite=False,
                     width=240, height=200):
    thumbnail_dir = os.path.join(settings.MEDIA_ROOT, 'thumbs')
    if not os.path.exists(thumbnail_dir):
        os.makedirs(thumbnail_dir)
    thumbnail_name = None
    if isinstance(instance, Layer):
        thumbnail_name = 'layer-%s-thumb.png' % instance.uuid
    elif isinstance(instance, Map):
        thumbnail_name = 'map-%s-thumb.png' % instance.uuid
    thumbnail_path = os.path.join(thumbnail_dir, thumbnail_name)
    if overwrite or not storage.exists(thumbnail_path):
        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        if not thumbnail_create_url:
            thumbnail_create_url = thumbnail_remote_url

        if check_bbox:
            # Check if the bbox is invalid
            valid_x = (
                float(
                    instance.bbox_x0) -
                float(
                    instance.bbox_x1)) ** 2 > BBOX_DIFFERENCE_THRESHOLD
            valid_y = (
                float(
                    instance.bbox_y1) -
                float(
                    instance.bbox_y0)) ** 2 > BBOX_DIFFERENCE_THRESHOLD
        else:
            valid_x = True
            valid_y = True

        image = None

        if valid_x and valid_y:
            Link.objects.get_or_create(resource=instance.get_self_resource(),
                                       url=thumbnail_remote_url,
                                       defaults=dict(
                                           extension='png',
                                           name="Remote Thumbnail",
                                           mime='image/png',
                                           link_type='image',
            )
            )
            ResourceBase.objects.filter(id=instance.id) \
                .update(thumbnail_url=thumbnail_remote_url)

            # Download thumbnail and save it locally.
            if not ogc_client:
                ogc_client = http_client

            if ogc_client:
                try:
                    params = {
                        'width': width,
                        'height': height
                    }
                    # Add the bbox param only if the bbox is different to [None, None,
                    # None, None]
                    if None not in instance.bbox:
                        params['bbox'] = instance.bbox_string
                        params['crs'] = instance.srid

                    for _p in params.keys():
                        if _p.lower() not in thumbnail_create_url.lower():
                            thumbnail_create_url = thumbnail_create_url + '&%s=%s' % (_p, params[_p])
                    resp, image = ogc_client.request(thumbnail_create_url)
                    if 'ServiceException' in image or \
                       resp.status_code < 200 or resp.status_code > 299:
                        msg = 'Unable to obtain thumbnail: %s' % image
                        logger.error(msg)

                        # Replace error message with None.
                        image = None
                except BaseException as e:
                    logger.exception(e)

                    # Replace error message with None.
                    image = None

            if check_ogc_backend(geoserver.BACKEND_PACKAGE):
                if image is None and instance.bbox:
                    instance_bbox = instance.bbox[0:4]
                    request_body = {
                        'bbox': [str(coord) for coord in instance_bbox],
                        'srid': instance.srid,
                        'width': width,
                        'height': height
                    }
                    if thumbnail_create_url:
                        request_body['thumbnail_create_url'] = thumbnail_create_url
                    elif instance.alternate:
                        request_body['layers'] = instance.alternate
                    image = _prepare_thumbnail_body_from_opts(request_body)

                if image is not None:
                    instance.save_thumbnail(thumbnail_name, image=image)
                else:
                    msg = 'Unable to obtain thumbnail for: %s' % instance
                    logger.error(msg)
Ejemplo n.º 6
0
    def test_ogc_server_defaults(self):
        """
        Tests that OGC_SERVER_SETTINGS are built if they do not exist in the settings.
        """

        OGC_SERVER = {'default': dict()}

        defaults = self.OGC_DEFAULT_SETTINGS.get('default')
        ogc_settings = OGC_Servers_Handler(OGC_SERVER)['default']
        self.assertEqual(ogc_settings.server, defaults)
        self.assertEqual(ogc_settings.rest, defaults['LOCATION'] + 'rest')
        self.assertEqual(ogc_settings.ows, defaults['LOCATION'] + 'ows')

        # Make sure we get None vs a KeyError when the key does not exist
        self.assertIsNone(ogc_settings.SFDSDFDSF)

        # Testing OWS endpoints
        from django.urls import reverse
        from ..ows import _wcs_get_capabilities, _wfs_get_capabilities, _wms_get_capabilities
        wcs = _wcs_get_capabilities()
        logger.debug(wcs)
        self.assertIsNotNone(wcs)

        try:
            wcs_url = urljoin(settings.SITEURL, reverse('ows_endpoint'))
        except BaseException:
            wcs_url = urljoin(ogc_settings.PUBLIC_LOCATION, 'ows')

        self.assertTrue(wcs.startswith(wcs_url))
        self.assertIn("service=WCS", wcs)
        self.assertIn("request=GetCapabilities", wcs)
        self.assertIn("version=2.0.1", wcs)

        wfs = _wfs_get_capabilities()
        logger.debug(wfs)
        self.assertIsNotNone(wfs)

        try:
            wfs_url = urljoin(settings.SITEURL, reverse('ows_endpoint'))
        except BaseException:
            wfs_url = urljoin(ogc_settings.PUBLIC_LOCATION, 'ows')
        self.assertTrue(wfs.startswith(wfs_url))
        self.assertIn("service=WFS", wfs)
        self.assertIn("request=GetCapabilities", wfs)
        self.assertIn("version=1.1.0", wfs)

        wms = _wms_get_capabilities()
        logger.debug(wms)
        self.assertIsNotNone(wms)

        try:
            wms_url = urljoin(settings.SITEURL, reverse('ows_endpoint'))
        except BaseException:
            wms_url = urljoin(ogc_settings.PUBLIC_LOCATION, 'ows')
        self.assertTrue(wms.startswith(wms_url))
        self.assertIn("service=WMS", wms)
        self.assertIn("request=GetCapabilities", wms)
        self.assertIn("version=1.3.0", wms)

        # Test OWS Download Links
        from geonode.geoserver.ows import wcs_links, wfs_links, wms_links
        instance = Layer.objects.all()[0]
        bbox = instance.bbox
        srid = instance.srid
        height = 512
        width = 512

        # Default Style (expect exception since we are offline)
        style = None
        with self.assertRaises(GeoNodeException):
            style = get_sld_for(gs_catalog, instance)
        self.assertIsNone(style)
        style = gs_catalog.get_style("line")
        self.assertIsNotNone(style)
        instance.default_style, _ = Style.objects.get_or_create(
            name=style.name,
            defaults=dict(
                sld_title=style.sld_title,
                sld_body=style.sld_body
            )
        )
        self.assertIsNotNone(instance.default_style)
        self.assertIsNotNone(instance.default_style.name)

        # WMS Links
        wms_links = wms_links(ogc_settings.public_url + 'wms?',
                              instance.alternate,
                              bbox,
                              srid,
                              height,
                              width)
        self.assertIsNotNone(wms_links)
        self.assertEquals(len(wms_links), 3)
        wms_url = urljoin(ogc_settings.PUBLIC_LOCATION, 'wms')
        identifier = urlencode({'layers': instance.alternate})
        for _link in wms_links:
            logger.debug('%s --> %s' % (wms_url, _link[3]))
            self.assertTrue(wms_url in _link[3])
            logger.debug('%s --> %s' % (identifier, _link[3]))
            self.assertTrue(identifier in _link[3])

        # WFS Links
        wfs_links = wfs_links(ogc_settings.public_url + 'wfs?',
                              instance.alternate,
                              bbox,
                              srid)
        self.assertIsNotNone(wfs_links)
        self.assertEquals(len(wfs_links), 6)
        wfs_url = urljoin(ogc_settings.PUBLIC_LOCATION, 'wfs')
        identifier = urlencode({'typename': instance.alternate})
        for _link in wfs_links:
            logger.debug('%s --> %s' % (wfs_url, _link[3]))
            self.assertTrue(wfs_url in _link[3])
            logger.debug('%s --> %s' % (identifier, _link[3]))
            self.assertTrue(identifier in _link[3])

        # WCS Links
        wcs_links = wcs_links(ogc_settings.public_url + 'wcs?',
                              instance.alternate,
                              bbox,
                              srid)
        self.assertIsNotNone(wcs_links)
        self.assertEquals(len(wcs_links), 2)
        wcs_url = urljoin(ogc_settings.PUBLIC_LOCATION, 'wcs')
        identifier = urlencode({'coverageid': instance.alternate})
        for _link in wcs_links:
            logger.debug('%s --> %s' % (wcs_url, _link[3]))
            self.assertTrue(wcs_url in _link[3])
            logger.debug('%s --> %s' % (identifier, _link[3]))
            self.assertTrue(identifier in _link[3])

        # Thumbnails Generation Default
        create_gs_thumbnail(instance, overwrite=True)
        self.assertIsNotNone(instance.get_thumbnail_url())

        # Thumbnails Generation Through "remote url"
        create_gs_thumbnail_geonode(instance, overwrite=True, check_bbox=True)

        # Thumbnails Generation Through "image"
        request_body = {
            'width': width,
            'height': height,
            'layers': instance.alternate
        }
        if hasattr(instance, 'default_style'):
            if instance.default_style:
                request_body['styles'] = instance.default_style.name
        self.assertIsNotNone(request_body['styles'])

        try:
            image = _prepare_thumbnail_body_from_opts(request_body)
        except BaseException as e:
            logger.exception(e)
            image = None
        # We are offline here, the layer does not exists in GeoServer
        # - we expect the image is None
        self.assertIsNone(image)
Ejemplo n.º 7
0
def create_thumbnail(instance,
                     thumbnail_remote_url,
                     thumbnail_create_url=None,
                     check_bbox=False,
                     ogc_client=None,
                     overwrite=False,
                     width=240,
                     height=200):
    thumbnail_dir = os.path.join(settings.MEDIA_ROOT, 'thumbs')
    if not os.path.exists(thumbnail_dir):
        os.makedirs(thumbnail_dir)
    thumbnail_name = None
    if isinstance(instance, Layer):
        thumbnail_name = 'layer-%s-thumb.png' % instance.uuid
    elif isinstance(instance, Map):
        thumbnail_name = 'map-%s-thumb.png' % instance.uuid
    thumbnail_path = os.path.join(thumbnail_dir, thumbnail_name)
    if overwrite or not storage.exists(thumbnail_path):
        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        if not thumbnail_create_url:
            thumbnail_create_url = thumbnail_remote_url

        if check_bbox:
            # Check if the bbox is invalid
            valid_x = (float(instance.bbox_x0) -
                       float(instance.bbox_x1))**2 > BBOX_DIFFERENCE_THRESHOLD
            valid_y = (float(instance.bbox_y1) -
                       float(instance.bbox_y0))**2 > BBOX_DIFFERENCE_THRESHOLD
        else:
            valid_x = True
            valid_y = True

        image = None

        if valid_x and valid_y:
            Link.objects.get_or_create(resource=instance.get_self_resource(),
                                       url=thumbnail_remote_url,
                                       defaults=dict(
                                           extension='png',
                                           name="Remote Thumbnail",
                                           mime='image/png',
                                           link_type='image',
                                       ))
            ResourceBase.objects.filter(id=instance.id) \
                .update(thumbnail_url=thumbnail_remote_url)

            # Download thumbnail and save it locally.
            if not ogc_client:
                ogc_client = http_client

            if ogc_client:
                try:
                    params = {'width': width, 'height': height}
                    # Add the bbox param only if the bbox is different to [None, None,
                    # None, None]
                    if None not in instance.bbox:
                        params['bbox'] = instance.bbox_string
                        params['crs'] = instance.srid

                    for _p in params.keys():
                        if _p.lower() not in thumbnail_create_url.lower():
                            thumbnail_create_url = thumbnail_create_url + '&%s=%s' % (
                                _p, params[_p])
                    headers = {}
                    if check_ogc_backend(geoserver.BACKEND_PACKAGE):
                        _ogc_server_settings = settings.OGC_SERVER['default']
                        _user = _ogc_server_settings[
                            'USER'] if 'USER' in _ogc_server_settings else 'admin'
                        _pwd = _ogc_server_settings[
                            'PASSWORD'] if 'PASSWORD' in _ogc_server_settings else 'geoserver'
                        import base64
                        valid_uname_pw = base64.b64encode(
                            b"%s:%s" % (_user, _pwd)).decode("ascii")
                        headers['Authorization'] = 'Basic {}'.format(
                            valid_uname_pw)
                    resp, image = ogc_client.request(thumbnail_create_url,
                                                     headers=headers)
                    if 'ServiceException' in image or \
                       resp.status_code < 200 or resp.status_code > 299:
                        msg = 'Unable to obtain thumbnail: %s' % image
                        logger.error(msg)

                        # Replace error message with None.
                        image = None
                except BaseException as e:
                    logger.exception(e)

                    # Replace error message with None.
                    image = None

            if check_ogc_backend(geoserver.BACKEND_PACKAGE):
                if image is None and instance.bbox:
                    instance_bbox = instance.bbox[0:4]
                    request_body = {
                        'bbox': [str(coord) for coord in instance_bbox],
                        'srid': instance.srid,
                        'width': width,
                        'height': height
                    }
                    if thumbnail_create_url:
                        request_body[
                            'thumbnail_create_url'] = thumbnail_create_url
                    elif instance.alternate:
                        request_body['layers'] = instance.alternate
                    image = _prepare_thumbnail_body_from_opts(request_body)

                if image is not None:
                    instance.save_thumbnail(thumbnail_name, image=image)
                else:
                    msg = 'Unable to obtain thumbnail for: %s' % instance
                    logger.error(msg)