예제 #1
0
class GraphDataView(View):

    action = "update_node"

    def get(self, request, graphid, nodeid=None):
        if self.action == "export_graph":
            graph = get_graphs_for_export([graphid])
            graph["metadata"] = system_metadata()
            f = JSONSerializer().serialize(graph, indent=4)
            graph_name = JSONDeserializer().deserialize(f)["graph"][0]["name"]

            response = HttpResponse(f, content_type="json/plain")
            response[
                "Content-Disposition"] = 'attachment; filename="%s.json"' % (
                    graph_name)
            return response
        elif self.action == "export_mapping_file":
            files_for_export = create_mapping_configuration_file(graphid, True)
            file_name = Graph.objects.get(graphid=graphid).name

            buffer = BytesIO()

            with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zip:
                for f in files_for_export:
                    f["outputfile"].seek(0)
                    zip.writestr(f["name"], f["outputfile"].read())

            zip.close()
            buffer.flush()
            zip_stream = buffer.getvalue()
            buffer.close()

            response = HttpResponse()
            response[
                "Content-Disposition"] = "attachment; filename=" + file_name + ".zip"
            response["Content-length"] = str(len(zip_stream))
            response["Content-Type"] = "application/zip"
            response.write(zip_stream)
            return response

        elif self.action == "get_domain_connections":
            res = []
            graph = Graph.objects.get(graphid=graphid)
            ret = graph.get_valid_domain_ontology_classes()
            for r in ret:
                res.append({
                    "ontology_property":
                    r["ontology_property"],
                    "ontology_classes": [c for c in r["ontology_classes"]]
                })
            return JSONResponse(res)

        elif self.action == "get_nodes":
            graph = Graph.objects.get(graphid=graphid)
            return JSONResponse(graph.nodes)

        elif self.action == "get_related_nodes":
            parent_nodeid = request.GET.get("parent_nodeid", None)
            graph = Graph.objects.get(graphid=graphid)
            ret = graph.get_valid_ontology_classes(nodeid=nodeid,
                                                   parent_nodeid=parent_nodeid)
            return JSONResponse(ret)

        elif self.action == "get_valid_domain_nodes":
            graph = Graph.objects.get(graphid=graphid)
            if nodeid == "":
                nodeid = None
            ret = graph.get_valid_domain_ontology_classes(nodeid=nodeid)
            return JSONResponse(ret)

        return HttpResponseNotFound()

    @method_decorator(group_required("Graph Editor"), name="dispatch")
    def post(self, request, graphid=None):
        ret = {}
        try:
            if self.action == "import_graph":
                graph_file = request.FILES.get("importedGraph").read()
                graphs = JSONDeserializer().deserialize(graph_file)["graph"]
                ret = GraphImporter.import_graph(graphs)
            else:
                if graphid is not None:
                    graph = Graph.objects.get(graphid=graphid)
                data = JSONDeserializer().deserialize(request.body)

                if self.action == "new_graph":
                    isresource = data[
                        "isresource"] if "isresource" in data else False
                    name = _("New Resource Model") if isresource else _(
                        "New Branch")
                    author = request.user.first_name + " " + request.user.last_name
                    ret = Graph.new(name=name,
                                    is_resource=isresource,
                                    author=author)

                elif self.action == "update_node":
                    old_node_data = graph.nodes.get(uuid.UUID(data["nodeid"]))
                    nodegroup_changed = str(
                        old_node_data.nodegroup_id) != data["nodegroup_id"]
                    updated_values = graph.update_node(data)
                    if "nodeid" in data and nodegroup_changed is False:
                        graph.save(nodeid=data["nodeid"])
                    else:
                        graph.save()
                    ret = JSONSerializer().serializeToPython(graph)
                    ret["updated_values"] = updated_values
                    ret["default_card_name"] = graph.temp_node_name

                elif self.action == "update_node_layer":
                    nodeid = uuid.UUID(str(data.get("nodeid")))
                    node = graph.nodes[nodeid]
                    node.config = data["config"]
                    ret = graph
                    node.save()

                elif self.action == "append_branch":
                    ret = graph.append_branch(data["property"],
                                              nodeid=data["nodeid"],
                                              graphid=data["graphid"])
                    ret = ret.serialize()
                    ret["nodegroups"] = graph.get_nodegroups()
                    ret["cards"] = graph.get_cards()
                    ret["widgets"] = graph.get_widgets()
                    graph.save()

                elif self.action == "append_node":
                    ret = graph.append_node(nodeid=data["nodeid"])
                    graph.save()

                elif self.action == "move_node":
                    ret = graph.move_node(data["nodeid"], data["property"],
                                          data["newparentnodeid"])
                    graph.save()

                elif self.action == "export_branch":
                    clone_data = graph.copy(root=data)
                    clone_data["copy"].slug = None
                    clone_data["copy"].save()
                    ret = {"success": True, "graphid": clone_data["copy"].pk}

                elif self.action == "clone_graph":
                    clone_data = graph.copy()
                    ret = clone_data["copy"]
                    ret.slug = None
                    ret.save()
                    ret.copy_functions(
                        graph, [clone_data["nodes"], clone_data["nodegroups"]])

                elif self.action == "reorder_nodes":
                    json = request.body
                    if json is not None:
                        data = JSONDeserializer().deserialize(json)

                        if "nodes" in data and len(data["nodes"]) > 0:
                            sortorder = 0
                            with transaction.atomic():
                                for node in data["nodes"]:
                                    no = models.Node.objects.get(
                                        pk=node["nodeid"])
                                    no.sortorder = sortorder
                                    no.save()
                                    sortorder = sortorder + 1
                            ret = data

            return JSONResponse(ret)
        except GraphValidationError as e:
            return JSONErrorResponse(e.title, e.message, {"status": "Failed"})
        except ModelInactiveError as e:
            return JSONErrorResponse(e.title, e.message)
        except RequestError as e:
            return JSONErrorResponse(
                _("Elasticsearch indexing error"),
                _("""If you want to change the datatype of an existing node.  
                    Delete and then re-create the node, or export the branch then edit the datatype and re-import the branch."""
                  ),
            )

    @method_decorator(group_required("Graph Editor"), name="dispatch")
    def delete(self, request, graphid):
        if self.action == "delete_node":
            data = JSONDeserializer().deserialize(request.body)
            try:
                graph = Graph.objects.get(graphid=graphid)
                graph.delete_node(node=data.get("nodeid", None))
                return JSONResponse({})
            except GraphValidationError as e:
                return JSONErrorResponse(e.title, e.message)
        elif self.action == "delete_instances":
            try:
                graph = Graph.objects.get(graphid=graphid)
                graph.delete_instances()
                return JSONResponse({
                    "success":
                    True,
                    "message":
                    "All the resources associated with the Model '{0}' have been successfully deleted."
                    .format(graph.name),
                    "title":
                    "Resources Successfully Deleted.",
                })
            except GraphValidationError as e:
                return JSONErrorResponse(e.title, e.message)
            except ModelInactiveError as e:
                return JSONErrorResponse(e.title, e.message)
        elif self.action == "delete_graph":
            try:
                graph = Graph.objects.get(graphid=graphid)
                if graph.isresource:
                    graph.delete_instances()
                    graph.isactive = False
                    graph.save(validate=False)
                graph.delete()
                return JSONResponse({"success": True})
            except GraphValidationError as e:
                return JSONErrorResponse(e.title, e.message)

        return HttpResponseNotFound()
예제 #2
0
                deleted = ret.delete(user=request.user)
            except ModelInactiveError as e:
                message = _("Unable to delete. Please verify the model status is active")
                return JSONResponse({"status": "false", "message": [_(e.title), _(str(message))]}, status=500)
            if deleted is True:
                return JSONResponse(ret)
            else:
                return JSONErrorResponse("Unable to Delete Resource", "Provisional users cannot delete resources with authoritative data")
        return HttpResponseNotFound()

    def copy(self, request, resourceid=None):
        resource_instance = Resource.objects.get(pk=resourceid)
        return JSONResponse(resource_instance.copy())


@method_decorator(group_required("Resource Editor"), name="dispatch")
class ResourcePermissionDataView(View):
    perm_cache = {}
    action = None

    def get(self, request):
        resourceid = request.GET.get("instanceid", None)
        resource_instance = models.ResourceInstance.objects.get(pk=resourceid)
        result = self.get_instance_permissions(resource_instance)
        return JSONResponse(result)

    def post(self, request):
        resourceid = request.POST.get("instanceid", None)
        result = None
        if self.action == "restrict":
            result = self.make_instance_private(resourceid)
예제 #3
0

class GraphBaseView(BaseManagerView):
    def get_context_data(self, **kwargs):
        context = super(GraphBaseView, self).get_context_data(**kwargs)
        try:
            context["graphid"] = self.graph.graphid
            context["graph"] = JSONSerializer().serializeToPython(self.graph)
            context["graph_json"] = JSONSerializer().serialize(self.graph)
            context["root_node"] = self.graph.node_set.get(istopnode=True)
        except Exception:
            pass
        return context


@method_decorator(group_required("Graph Editor"), name="dispatch")
class GraphSettingsView(GraphBaseView):
    def get(self, request, graphid):
        self.graph = models.GraphModel.objects.get(graphid=graphid)
        icons = models.Icon.objects.order_by("name")
        resource_graphs = models.GraphModel.objects.filter(
            Q(isresource=True)).exclude(
                graphid=settings.SYSTEM_SETTINGS_RESOURCE_MODEL_ID)
        resource_data = []
        node = models.Node.objects.get(graph_id=graphid, istopnode=True)
        relatable_resources = node.get_relatable_resources()
        for res in resource_graphs:
            if models.Node.objects.filter(graph=res,
                                          istopnode=True).count() > 0:
                node_model = models.Node.objects.get(graph=res, istopnode=True)
                resource_data.append({
예제 #4
0
파일: graph.py 프로젝트: mrcnc/arches

class GraphBaseView(BaseManagerView):
    def get_context_data(self, **kwargs):
        context = super(GraphBaseView, self).get_context_data(**kwargs)
        try:
            context['graphid'] = self.graph.graphid
            context['graph'] = JSONSerializer().serializeToPython(self.graph)
            context['graph_json'] = JSONSerializer().serialize(self.graph)
            context['root_node'] = self.graph.node_set.get(istopnode=True)
        except:
            pass
        return context


@method_decorator(group_required('Graph Editor'), name='dispatch')
class GraphSettingsView(GraphBaseView):
    def get(self, request, graphid):
        self.graph = Graph.objects.get(graphid=graphid)
        icons = models.Icon.objects.order_by('name')
        resource_graphs = models.GraphModel.objects.filter(
            Q(isresource=True)).exclude(
                graphid=settings.SYSTEM_SETTINGS_RESOURCE_MODEL_ID)
        resource_data = []
        node = models.Node.objects.get(graph_id=graphid, istopnode=True)
        relatable_resources = node.get_relatable_resources()
        for res in resource_graphs:
            if models.Node.objects.filter(graph=res,
                                          istopnode=True).count() > 0:
                node_model = models.Node.objects.get(graph=res, istopnode=True)
                resource_data.append({
예제 #5
0
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
from arches.app.models import models
from arches.app.models.system_settings import settings
from arches.app.models.concept import Concept, ConceptValue, CORE_CONCEPTS, get_preflabel_from_valueid
from arches.app.search.search_engine_factory import SearchEngineFactory
from arches.app.search.elasticsearch_dsl_builder import Bool, Match, Query, Nested, Terms, GeoShape, Range, SimpleQueryString
from arches.app.utils.decorators import group_required
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.response import JSONResponse
from arches.app.utils.skos import SKOSWriter, SKOSReader
from arches.app.views.base import BaseManagerView

@method_decorator(group_required('RDM Administrator'), name='dispatch')
class RDMView(BaseManagerView):
    def get(self, request, conceptid):
        lang = request.GET.get('lang', settings.LANGUAGE_CODE)

        languages = sort_languages(models.DLanguage.objects.all(), lang)

        concept_schemes = []
        for concept in models.Concept.objects.filter(nodetype='ConceptScheme'):
            concept_schemes.append(Concept().get(id=concept.pk, include=['label']).get_preflabel(lang=lang))

        collections = []
        for concept in models.Concept.objects.filter(nodetype='Collection'):
            collections.append(Concept().get(id=concept.pk, include=['label']).get_preflabel(lang=lang))

        context = self.get_context_data(
예제 #6
0
class GraphDataView(View):

    action = 'update_node'

    def get(self, request, graphid, nodeid=None):
        if self.action == 'export_graph':
            graph = get_graphs_for_export([graphid])
            graph['metadata'] = system_metadata()
            f = JSONSerializer().serialize(graph, indent=4)
            graph_name = JSONDeserializer().deserialize(f)['graph'][0]['name']

            response = HttpResponse(f, content_type='json/plain')
            response[
                'Content-Disposition'] = 'attachment; filename="%s.json"' % (
                    graph_name)
            return response
        elif self.action == 'export_mapping_file':
            files_for_export = create_mapping_configuration_file(graphid, True)
            file_name = Graph.objects.get(graphid=graphid).name

            buffer = StringIO()

            with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) as zip:
                for f in files_for_export:
                    f['outputfile'].seek(0)
                    zip.writestr(f['name'], f['outputfile'].read())

            zip.close()
            buffer.flush()
            zip_stream = buffer.getvalue()
            buffer.close()

            response = HttpResponse()
            response[
                'Content-Disposition'] = 'attachment; filename=' + file_name + '.zip'
            response['Content-length'] = str(len(zip_stream))
            response['Content-Type'] = 'application/zip'
            response.write(zip_stream)
            return response

        elif self.action == 'get_domain_connections':
            res = []
            graph = Graph.objects.get(graphid=graphid)
            ontology_class = request.GET.get('ontology_class', None)
            ret = graph.get_valid_domain_ontology_classes()
            for r in ret:
                res.append({
                    'ontology_property':
                    r['ontology_property'],
                    'ontology_classes': [c for c in r['ontology_classes']]
                })
            return JSONResponse(res)

        else:
            graph = Graph.objects.get(graphid=graphid)
            if self.action == 'get_related_nodes':
                parent_nodeid = request.GET.get('parent_nodeid', None)
                ret = graph.get_valid_ontology_classes(
                    nodeid=nodeid, parent_nodeid=parent_nodeid)

            elif self.action == 'get_valid_domain_nodes':
                if nodeid == '':
                    nodeid = None
                ret = graph.get_valid_domain_ontology_classes(nodeid=nodeid)

            return JSONResponse(ret)

        return HttpResponseNotFound()

    @method_decorator(group_required('Graph Editor'), name='dispatch')
    def post(self, request, graphid=None):
        ret = {}
        try:
            if self.action == 'import_graph':
                graph_file = request.FILES.get('importedGraph').read()
                graphs = JSONDeserializer().deserialize(graph_file)['graph']
                ret = GraphImporter.import_graph(graphs)
            else:
                if graphid is not None:
                    graph = Graph.objects.get(graphid=graphid)
                data = JSONDeserializer().deserialize(request.body)

                if self.action == 'new_graph':
                    isresource = data[
                        'isresource'] if 'isresource' in data else False
                    name = _('New Resource Model') if isresource else _(
                        'New Branch')
                    author = request.user.first_name + ' ' + request.user.last_name
                    ret = Graph.new(name=name,
                                    is_resource=isresource,
                                    author=author)

                elif self.action == 'update_node':
                    updated_values = graph.update_node(data)
                    graph.save()
                    ret = JSONSerializer().serializeToPython(graph)
                    ret['updated_values'] = updated_values

                elif self.action == 'update_node_layer':
                    nodeid = uuid.UUID(str(data.get('nodeid')))
                    node = graph.nodes[nodeid]
                    node.config = data['config']
                    ret = graph
                    node.save()

                elif self.action == 'append_branch':
                    ret = graph.append_branch(data['property'],
                                              nodeid=data['nodeid'],
                                              graphid=data['graphid'])
                    ret = ret.serialize()
                    ret['nodegroups'] = graph.get_nodegroups()
                    ret['cards'] = graph.get_cards()
                    ret['widgets'] = graph.get_widgets()
                    graph.save()

                elif self.action == 'append_node':
                    ret = graph.append_node(nodeid=data['nodeid'])
                    graph.save()

                elif self.action == 'move_node':
                    ret = graph.move_node(data['nodeid'], data['property'],
                                          data['newparentnodeid'])
                    graph.save()

                elif self.action == 'export_branch':
                    clone_data = graph.copy(root=data)
                    clone_data['copy'].save()
                    ret = {'success': True, 'graphid': clone_data['copy'].pk}

                elif self.action == 'clone_graph':
                    clone_data = graph.copy()
                    ret = clone_data['copy']
                    ret.save()
                    ret.copy_functions(
                        graph, [clone_data['nodes'], clone_data['nodegroups']])

                elif self.action == 'reorder_nodes':
                    json = request.body
                    if json is not None:
                        data = JSONDeserializer().deserialize(json)

                        if 'nodes' in data and len(data['nodes']) > 0:
                            sortorder = 0
                            with transaction.atomic():
                                for node in data['nodes']:
                                    no = models.Node.objects.get(
                                        pk=node['nodeid'])
                                    no.sortorder = sortorder
                                    no.save()
                                    sortorder = sortorder + 1
                            ret = data

            return JSONResponse(ret)
        except GraphValidationError as e:
            return JSONResponse(
                {
                    'status': 'false',
                    'success': False,
                    'message': e.message,
                    'title': e.title
                },
                status=500)

    @method_decorator(group_required('Graph Editor'), name='dispatch')
    def delete(self, request, graphid):
        if self.action == 'delete_node':
            data = JSONDeserializer().deserialize(request.body)
            try:
                graph = Graph.objects.get(graphid=graphid)
                graph.delete_node(node=data.get('nodeid', None))
                return JSONResponse({})
            except GraphValidationError as e:
                return JSONResponse(
                    {
                        'status': 'false',
                        'message': e.message,
                        'title': e.title
                    },
                    status=500)
        elif self.action == 'delete_instances':
            try:
                graph = Graph.objects.get(graphid=graphid)
                graph.delete_instances()
                return JSONResponse({
                    'success':
                    True,
                    'message':
                    "All the resources associated with the Model '{0}' have been successfully deleted."
                    .format(graph.name),
                    'title':
                    "Resources Successfully Deleted."
                })
            except GraphValidationError as e:
                return JSONResponse(
                    {
                        'status': 'false',
                        'message': e.message,
                        'title': e.title
                    },
                    status=500)
        elif self.action == 'delete_graph':
            try:
                graph = Graph.objects.get(graphid=graphid)
                if graph.isresource:
                    graph.isactive = False
                    graph.save(validate=False)
                    graph.delete_instances()
                graph.delete()
                return JSONResponse({'success': True})
            except GraphValidationError as e:
                return JSONResponse(
                    {
                        'status': 'false',
                        'message': e.message,
                        'title': e.title
                    },
                    status=500)

        return HttpResponseNotFound()
예제 #7
0
파일: map.py 프로젝트: msrivastava/arches
from revproxy.views import ProxyView
from arches.app.models import models
from arches.app.models.system_settings import settings
from arches.app.models.card import Card
from arches.app.views.base import BaseManagerView, MapBaseManagerView
from arches.app.datatypes.datatypes import DataTypeFactory
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.decorators import group_required
from arches.app.utils.response import JSONResponse
from arches.app.utils.permission_backend import get_users_for_object, get_groups_for_object
from arches.app.search.search_engine_factory import SearchEngineFactory
from arches.app.search.elasticsearch_dsl_builder import Query, Bool, GeoBoundsAgg, Term
from arches.app.search.mappings import RESOURCES_INDEX


@method_decorator(group_required("Application Administrator"), name="dispatch")
class MapLayerManagerView(MapBaseManagerView):
    def get(self, request):
        se = SearchEngineFactory().create()
        datatype_factory = DataTypeFactory()
        datatypes = models.DDataType.objects.all()
        widgets = models.Widget.objects.all()
        map_layers = models.MapLayer.objects.all()
        map_markers = models.MapMarker.objects.all()
        map_sources = models.MapSource.objects.all()
        icons = models.Icon.objects.order_by("name")
        context = self.get_context_data(
            icons=JSONSerializer().serialize(icons),
            datatypes=datatypes,
            widgets=widgets,
            map_layers=map_layers,
예제 #8
0
파일: graph.py 프로젝트: fargeo/arches
    return ontology_namespaces


class GraphBaseView(BaseManagerView):
    def get_context_data(self, **kwargs):
        context = super(GraphBaseView, self).get_context_data(**kwargs)
        try:
            context['graphid'] = self.graph.graphid
            context['graph'] = JSONSerializer().serializeToPython(self.graph)
            context['graph_json'] = JSONSerializer().serialize(self.graph)
            context['root_node'] = self.graph.node_set.get(istopnode=True)
        except:
            pass
        return context

@method_decorator(group_required('Graph Editor'), name='dispatch')
class GraphSettingsView(GraphBaseView):
    def get(self, request, graphid):
        self.graph = Graph.objects.get(graphid=graphid)
        icons = models.Icon.objects.order_by('name')
        resource_graphs = models.GraphModel.objects.filter(Q(isresource=True)).exclude(graphid=settings.SYSTEM_SETTINGS_RESOURCE_MODEL_ID)
        resource_data = []
        node = models.Node.objects.get(graph_id=graphid, istopnode=True)
        relatable_resources = node.get_relatable_resources()
        for res in resource_graphs:
            if models.Node.objects.filter(graph=res, istopnode=True).count() > 0:
                node_model = models.Node.objects.get(graph=res, istopnode=True)
                resource_data.append({
                    'id': node_model.nodeid,
                    'graph': res,
                    'is_relatable': (node_model in relatable_resources)
예제 #9
0
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.views.generic import View
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.response import JSONResponse
from arches.app.utils.decorators import group_required
from arches.app.utils.geo_utils import GeoUtils
from arches.app.utils.couch import Couch
from arches.app.models import models
from arches.app.models.card import Card
from arches.app.models.mobile_survey import MobileSurvey
from arches.app.models.system_settings import settings
from arches.app.views.base import MapBaseManagerView
import arches.app.views.search as search

@method_decorator(group_required('Application Administrator'), name='dispatch')
class MobileSurveyManagerView(MapBaseManagerView):

    def get(self, request):

        def get_last_login(date):
            result = _("Not yet logged in")
            try:
                if date is not None:
                    result = datetime.strftime(date, '%Y-%m-%d %H:%M')
            except TypeError as e:
                print e
            return result

        identities = []
        for group in Group.objects.all():
예제 #10
0
from arches.app.models import models
from arches.app.models.forms import Form
from arches.app.models.card import Card
from arches.app.models.graph import Graph
from arches.app.models.resource import Resource
from arches.app.views.base import BaseManagerView
from arches.app.utils.decorators import group_required
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.JSONResponse import JSONResponse
from arches.app.search.search_engine_factory import SearchEngineFactory
from arches.app.search.elasticsearch_dsl_builder import Query, Terms
from arches.app.views.concept import Concept
from elasticsearch import Elasticsearch


@method_decorator(group_required('Resource Editor'), name='dispatch')
class ResourceListView(BaseManagerView):
    def get(self, request, graphid=None, resourceid=None):
        context = self.get_context_data(main_script='views/resource', )

        context['nav']['icon'] = "fa fa-bookmark"
        context['nav']['title'] = "Resource Manager"
        context['nav']['edit_history'] = True
        context['nav']['login'] = True
        context['nav']['help'] = (_('Creating and Editing Resources'), '')

        return render(request, 'views/resource.htm', context)


@method_decorator(group_required('Resource Editor'), name='dispatch')
class ResourceEditorView(BaseManagerView):
예제 #11
0
파일: concept.py 프로젝트: legiongis/arches
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
from arches.app.models import models
from arches.app.models.system_settings import settings
from arches.app.models.concept import Concept, ConceptValue, CORE_CONCEPTS, get_preflabel_from_valueid
from arches.app.search.search_engine_factory import SearchEngineInstance as se
from arches.app.search.elasticsearch_dsl_builder import Bool, Match, Query, Nested, Terms, GeoShape, Range, SimpleQueryString
from arches.app.search.mappings import CONCEPTS_INDEX
from arches.app.utils.decorators import group_required
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.response import JSONResponse, JSONErrorResponse
from arches.app.utils.skos import SKOSWriter, SKOSReader
from arches.app.views.base import BaseManagerView


@method_decorator(group_required("RDM Administrator"), name="dispatch")
class RDMView(BaseManagerView):
    def get(self, request, conceptid):
        lang = request.GET.get("lang", request.LANGUAGE_CODE)

        languages = sort_languages(models.DLanguage.objects.all(), lang)

        concept_schemes = []
        for concept in models.Concept.objects.filter(nodetype="ConceptScheme"):
            concept_schemes.append(Concept().get(
                id=concept.pk, include=["label"]).get_preflabel(lang=lang))

        collections = []
        for concept in models.Concept.objects.filter(nodetype="Collection"):
            collections.append(Concept().get(
                id=concept.pk, include=["label"]).get_preflabel(lang=lang))
예제 #12
0
파일: map.py 프로젝트: azerbini/eamena
'''
from django.db import transaction
from django.shortcuts import render
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from guardian.shortcuts import get_users_with_perms
from arches.app.models import models
from arches.app.models.card import Card
from arches.app.views.base import BaseManagerView
from arches.app.datatypes.datatypes import DataTypeFactory
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.decorators import group_required
from arches.app.utils.JSONResponse import JSONResponse


@method_decorator(group_required('Application Administrator'), name='dispatch')
class MapLayerManagerView(BaseManagerView):
    def get(self, request):
        datatype_factory = DataTypeFactory()
        datatypes = models.DDataType.objects.all()
        widgets = models.Widget.objects.all()
        map_layers = models.MapLayer.objects.all()
        map_sources = models.MapSource.objects.all()
        icons = models.Icon.objects.order_by('name')
        context = self.get_context_data(
            icons=JSONSerializer().serialize(icons),
            datatypes=datatypes,
            widgets=widgets,
            map_layers=map_layers,
            map_sources=map_sources,
            datatypes_json=JSONSerializer().serialize(datatypes),
예제 #13
0
파일: tile.py 프로젝트: azerbini/eamena
import uuid, importlib
from arches.app.datatypes.datatypes import DataTypeFactory
from arches.app.models import models
from arches.app.models.tile import Tile
from arches.app.utils.JSONResponse import JSONResponse
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.decorators import group_required
from arches.app.views.tileserver import clean_resource_cache
from django.http import HttpResponseNotFound
from django.utils.decorators import method_decorator
from django.core.exceptions import ValidationError
from django.views.generic import View
from django.db import transaction
from django.conf import settings

@method_decorator(group_required('Resource Editor'), name='dispatch')
class TileData(View):
    action = 'update_tile'

    def post(self, request):
        if self.action == 'update_tile':
            json = request.POST.get('data', None)
            if json != None:
                data = JSONDeserializer().deserialize(json)
                tile_id = data['tileid']
                if tile_id != None and tile_id != '':
                    old_tile = Tile.objects.get(pk=tile_id)
                    clean_resource_cache(old_tile)
                tile = Tile(data)
                with transaction.atomic():
                    try:
예제 #14
0
파일: concept.py 프로젝트: fargeo/arches
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
from arches.app.models import models
from arches.app.models.system_settings import settings
from arches.app.models.concept import Concept, ConceptValue, CORE_CONCEPTS, get_preflabel_from_valueid
from arches.app.search.search_engine_factory import SearchEngineFactory
from arches.app.search.elasticsearch_dsl_builder import Bool, Match, Query, Nested, Terms, GeoShape, Range, SimpleQueryString
from arches.app.utils.decorators import group_required
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.response import JSONResponse
from arches.app.utils.skos import SKOSWriter, SKOSReader
from arches.app.views.base import BaseManagerView

@method_decorator(group_required('RDM Administrator'), name='dispatch')
class RDMView(BaseManagerView):
    def get(self, request, conceptid):
        lang = request.GET.get('lang', settings.LANGUAGE_CODE)

        languages = sort_languages(models.DLanguage.objects.all(), lang)

        concept_schemes = []
        for concept in models.Concept.objects.filter(nodetype='ConceptScheme'):
            concept_schemes.append(Concept().get(id=concept.pk, include=['label']).get_preflabel(lang=lang))

        collections = []
        for concept in models.Concept.objects.filter(nodetype='Collection'):
            collections.append(Concept().get(id=concept.pk, include=['label']).get_preflabel(lang=lang))

        context = self.get_context_data(
예제 #15
0

class GraphBaseView(BaseManagerView):
    def get_context_data(self, **kwargs):
        context = super(GraphBaseView, self).get_context_data(**kwargs)
        try:
            context['graphid'] = self.graph.graphid
            context['graph'] = JSONSerializer().serializeToPython(self.graph)
            context['graph_json'] = JSONSerializer().serialize(self.graph)
            context['root_node'] = self.graph.node_set.get(istopnode=True)
        except:
            pass
        return context


@method_decorator(group_required('edit'), name='dispatch')
class GraphSettingsView(GraphBaseView):
    def get(self, request, graphid):
        self.graph = Graph.objects.get(graphid=graphid)
        icons = models.Icon.objects.order_by('name')
        resource_graphs = models.GraphModel.objects.filter(Q(isresource=True), ~Q(graphid=graphid))
        resource_data = []
        node = models.Node.objects.get(graph_id=graphid, istopnode=True)
        relatable_resources = node.get_relatable_resources()
        for res in resource_graphs:
            if models.Node.objects.filter(graph=res, istopnode=True).count() > 0:
                node_model = models.Node.objects.get(graph=res, istopnode=True)
                resource_data.append({
                    'id': node_model.nodeid,
                    'graph': res,
                    'is_relatable': (node_model in relatable_resources)
예제 #16
0
파일: graph.py 프로젝트: webjunkie/arches

class GraphBaseView(BaseManagerView):
    def get_context_data(self, **kwargs):
        context = super(GraphBaseView, self).get_context_data(**kwargs)
        try:
            context['graphid'] = self.graph.graphid
            context['graph'] = JSONSerializer().serializeToPython(self.graph)
            context['graph_json'] = JSONSerializer().serialize(self.graph)
            context['root_node'] = self.graph.node_set.get(istopnode=True)
        except:
            pass
        return context


@method_decorator(group_required('edit'), name='dispatch')
class GraphSettingsView(GraphBaseView):
    def get(self, request, graphid):
        self.graph = Graph.objects.get(graphid=graphid)
        icons = models.Icon.objects.order_by('name')
        resource_graphs = models.GraphModel.objects.filter(
            Q(isresource=True), ~Q(graphid=graphid))
        resource_data = []
        node = models.Node.objects.get(graph_id=graphid, istopnode=True)
        relatable_resources = node.get_relatable_resources()
        for res in resource_graphs:
            if models.Node.objects.filter(graph=res,
                                          istopnode=True).count() > 0:
                node_model = models.Node.objects.get(graph=res, istopnode=True)
                resource_data.append({
                    'id':