Ejemplo n.º 1
0
    def post(self, request):
        user, profile = user_and_profile(request)

        instance = get_object_or_404(Organisation, id=request.GET.get('id'))

        is_admin = profile.is_admin
        is_referent = LiaisonsReferents.objects.filter(
            profile=profile, organisation=instance,
            validated_on__isnull=False) and True or False

        if is_referent or is_admin:
            json = {
                'abstract': request.POST.get('abstract', None),
                'srs': [crs.authority for crs in SupportedCrs.objects.all()],
                'title': request.POST.get('title', None)
            }
            try:
                MRAHandler.update_ows_settings('ows',
                                               json,
                                               ws_name=instance.slug)
            except Exception as e:
                messages.error(request, e.__str__())
            else:
                messages.success(request, "Le service OGC est mis à jour.")
            return JsonResponse(data={})
        raise Http404()
Ejemplo n.º 2
0
    def post(self, request):
        id = request.GET.get('id')
        if not id:
            raise Http404()
        organisation = get_object_or_404(Organisation, id=id)

        user = request.user
        profile = user.profile

        is_admin = profile.is_admin
        is_referent = LiaisonsReferents.objects.filter(
            profile=profile, organisation__id=id,
            validated_on__isnull=False) and True or False

        if not (is_referent or is_admin):
            raise Http404()

        json = {
            'abstract': request.POST.get('abstract', None),
            'srs': [crs.authority for crs in SupportedCrs.objects.all()],
            'title': request.POST.get('title', None),
        }

        try:
            MRAHandler.update_ows_settings('ows',
                                           json,
                                           ws_name=organisation.slug)
        except Exception as e:
            messages.error(request, e.__str__())
        else:
            messages.success(request,
                             "Le service OGC a été mis à jour avec succès.")

        return redirect('idgo_admin:show_organisation', id=id)
Ejemplo n.º 3
0
    def post(self,
             request,
             dataset_id=None,
             resource_id=None,
             layer_id=None,
             *args,
             **kwargs):

        sld = request.POST.get('sldBody')

        try:
            MRAHandler.create_or_update_style(layer_id,
                                              data=sld.encode('utf-8'))
            MRAHandler.update_layer_defaultstyle(layer_id, layer_id)
        except ValidationError as e:
            messages.error(request, ' '.join(e))
        except MraBaseError as e:
            messages.error(request, e.__str__())
        else:
            message = 'Le style a été mis à jour avec succès.'
            messages.success(request, message)

        return HttpResponseRedirect(
            reverse('idgo_admin:layer_style_editor',
                    kwargs={
                        'dataset_id': dataset_id,
                        'resource_id': resource_id,
                        'layer_id': layer_id,
                    }))
Ejemplo n.º 4
0
    def post(self, request, dataset_id=None, resource_id=None, layer_id=None, *args, **kwargs):

        user, profile = user_and_profile(request)

        layer = get_object_or_404(Layer, resource=resource_id)
        form = Form(request.POST, instance=layer, include={'user': user})

        context = {
            'form': form,
            'layer': layer,
            }

        if not form.is_valid():
            return render_with_info_profile(request, self.template, context=context)

        try:
            MRAHandler.update_layer(layer_id, {
                'name': layer_id,
                'title': form.cleaned_data['title'],
                'abstract': form.cleaned_data['abstract'],
                })
        except ValidationError as e:
            messages.error(request, ' '.join(e))
        except MraBaseError as e:
            messages.error(request, e.__str__())
        else:
            messages.success(request, 'Les informations ont été mise à jour avec succès.')

        return HttpResponseRedirect(reverse('idgo_admin:layer_editor', kwargs={
            'dataset_id': dataset_id,
            'resource_id': resource_id,
            'layer_id': layer_id,
            }))
Ejemplo n.º 5
0
 def handle_enable_ows_status(self):
     """Gérer le statut d'activation de la couche de données SIG."""
     ws_name = self.resource.dataset.organisation.slug
     if self.resource.ogc_services:
         MRAHandler.enable_layer(ws_name, self.name)
         # TODO: Comment on gère les ressources CKAN service ???
     else:
         MRAHandler.disable_layer(ws_name, self.name)
Ejemplo n.º 6
0
    def put(self, request, dataset_name, resource_id, layer_name):
        if not request.content_type == 'application/vnd.ogc.sld+xml':
            raise Http404()

        try:
            resource_id = UUID(resource_id)
        except ValueError:
            raise Http404()
        sld = request.body
        MRAHandler.create_or_update_style(layer_name, data=sld)
        MRAHandler.update_layer_defaultstyle(layer_name, layer_name)

        return HttpResponse(status=204)
Ejemplo n.º 7
0
    def handle_layergroup(self):
        dataset = self.resource.dataset
        layers = list(
            itertools.chain.from_iterable([
                qs for qs in [
                    resource.get_layers()
                    for resource in dataset.get_resources()
                ]
            ]))
        # TODO remplacer par `layers = dataset.get_layers()`

        MRAHandler.create_or_update_layergroup(
            dataset.organisation.slug, {
                'name': dataset.slug,
                'title': dataset.title,
                'abstract': dataset.description,
                'layers': [layer.name for layer in layers]
            })
Ejemplo n.º 8
0
    def delete(self, *args, current_user=None, **kwargs):
        with_user = current_user

        # On supprime la ressource CKAN
        if with_user:
            username = with_user.username
            apikey = CkanHandler.get_user(username)['apikey']
            with CkanUserHandler(apikey=apikey) as ckan_user:
                ckan_user.delete_resource(self.name)
        else:
            CkanHandler.delete_resource(self.name)

        # On supprime les ressources MRA
        try:
            MRAHandler.del_layer(self.name)
            ws_name = self.resource.dataset.organisation.slug
            if self.type == 'vector':
                MRAHandler.del_featuretype(ws_name, 'public', self.name)
            if self.type == 'raster':
                MRAHandler.del_coverage(ws_name, self.name, self.name)
                # MRAHandler.del_coveragestore(ws_name, self.name)
        except Exception as e:
            logger.error(e)
            pass

        # On supprime la table de données PostGIS
        try:
            drop_table(self.name)
        except Exception as e:
            logger.error(e)
            pass

        # Puis on supprime l'instance
        super().delete(*args, **kwargs)
Ejemplo n.º 9
0
    def get(self, request, dataset_id=None, resource_id=None, layer_id=None, *args, **kwargs):
        user, profile = user_and_profile(request)
        layer = get_object_or_404(Layer, resource=resource_id)
        target = datasets_target(layer.resource.dataset, user)
        context = {
            'target': target,
            'layer': layer,
            'fonts_asjson': json.dumps(MRAHandler.get_fonts()),
            'layer_asjson': json.dumps(layer.mra_info),
            }

        return render_with_info_profile(
            request, 'idgo_admin/dataset/resource/layer/style/edit.html', context=context)
Ejemplo n.º 10
0
 def ows_settings(self):
     if MRAHandler.is_workspace_exists(self.slug):
         return MRAHandler.get_ows_settings('ows', self.slug)
Ejemplo n.º 11
0
 def ows_url(self):
     if MRAHandler.is_workspace_exists(self.slug):
         return OWS_URL_PATTERN.format(organisation=self.slug)
Ejemplo n.º 12
0
    def save_vector_layer(self, *args, **kwargs):
        """Synchronizer la couche de données vectorielle avec le service OGC via MRA."""
        organisation = self.resource.dataset.organisation
        ws_name = organisation.slug
        ds_name = 'public'

        if self.pk:
            try:
                Layer.objects.get(pk=self.pk)
            except Layer.DoesNotExist:
                pass
            else:
                # On vérifie si l'organisation du jeu de données a changée,
                # auquel cas il est nécessaire de supprimer les objets MRA
                # afin de les recréer dans le bon workspace (c-à-d Mapfile).
                previous_layer = MRAHandler.get_layer(self.name)
                regex = '/workspaces/(?P<ws_name>[a-z_\-]+)/datastores/'

                matched = re.search(regex, previous_layer['resource']['href'])
                if matched:
                    previous_ws_name = matched.group('ws_name')
                    if not ws_name == previous_ws_name:
                        MRAHandler.del_layer(self.name)
                        MRAHandler.del_featuretype(previous_ws_name, ds_name,
                                                   self.name)

        MRAHandler.get_or_create_workspace(organisation)
        MRAHandler.get_or_create_datastore(ws_name, ds_name)
        MRAHandler.get_or_create_featuretype(
            ws_name,
            ds_name,
            self.name,
            enabled=True,
            title=self.resource.title,
            abstract=self.resource.description)
Ejemplo n.º 13
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        organisation = self.resource.dataset.organisation
        ws_name = organisation.slug

        try:
            l = MRAHandler.get_layer(self.name)
        except MraBaseError:
            return

        # Récupération des informations de couche vecteur
        # ===============================================

        if self.type == 'vector':
            try:
                ft = MRAHandler.get_featuretype(ws_name, 'public', self.name)
            except MraBaseError:
                return
            if not l or not ft:
                return

            ll = ft['featureType']['latLonBoundingBox']
            bbox = [[ll['miny'], ll['minx']], [ll['maxy'], ll['maxx']]]
            attributes = [
                item['name'] for item in ft['featureType']['attributes']
            ]
            default_style_name = l['defaultStyle']['name']
            styles = [{
                'name': 'default',
                'text': 'Style par défaut',
                'url': l['defaultStyle']['href'].replace('json', 'sld'),
                'sld': MRAHandler.get_style(l['defaultStyle']['name'])
            }]
            if l.get('styles'):
                for style in l.get('styles')['style']:
                    styles.append({
                        'name': style['name'],
                        'text': style['name'],
                        'url': style['href'].replace('json', 'sld'),
                        'sld': MRAHandler.get_style(style['name'])
                    })

        # Récupération des informations de couche raster
        # ==============================================

        elif self.type == 'raster':
            try:
                c = MRAHandler.get_coverage(ws_name, self.name, self.name)
            except MraBaseError:
                return
            if not l or not c:
                return

            ll = c['coverage']['latLonBoundingBox']
            bbox = [[ll['miny'], ll['minx']], [ll['maxy'], ll['maxx']]]
            attributes = []
            default_style_name = None
            styles = []

        # Puis..
        self.mra_info = {
            'name': l['name'],
            'title': l['title'],
            'type': l['type'],
            'enabled': l['enabled'],
            'abstract': l['abstract'],
            'bbox': bbox,
            'attributes': attributes,
            'styles': {
                'default': default_style_name,
                'styles': styles
            }
        }
Ejemplo n.º 14
0
 def get_default_sld(self):
     style = MRAHandler.get_layer(self.name)['defaultStyle']
     if style:
         return MRAHandler.get_style(style['name'])