Esempio n. 1
0
    def copy(self):
        """
        Returns a copy of this resource instance includeing a copy of all tiles associated with this resource instance

        """
        # need this here to prevent a circular import error
        from arches.app.models.tile import Tile

        id_map = {}
        new_resource = Resource()
        new_resource.graph = self.graph

        if len(self.tiles) == 0:
            self.tiles = Tile.objects.filter(resourceinstance=self)

        for tile in self.tiles:
            new_tile = Tile()
            new_tile.data = tile.data
            new_tile.nodegroup = tile.nodegroup
            new_tile.parenttile = tile.parenttile
            new_tile.resourceinstance = new_resource
            new_tile.sortorder = tile.sortorder

            new_resource.tiles.append(new_tile)
            id_map[tile.pk] = new_tile

        for tile in new_resource.tiles:
            if tile.parenttile:
                tile.parenttile = id_map[tile.parenttile_id]

        with transaction.atomic():
            new_resource.save()

        return new_resource
Esempio n. 2
0
    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)
                if tile.filter_by_perm(request.user, 'write_nodegroup'):
                    with transaction.atomic():
                        try:
                            tile.save(request=request)
                        except ValidationError as e:
                            return JSONResponse({'status':'false','message':e.args}, status=500)
                        tile.after_update_all()
                        clean_resource_cache(tile)
                        update_system_settings_cache(tile)
                    return JSONResponse(tile)
                else:
                    return JSONResponse({'status':'false','message': [_('Request Failed'), _('Permission Denied')]}, status=500)

        if self.action == 'reorder_tiles':
            json = request.body
            if json != None:
                data = JSONDeserializer().deserialize(json)

                if 'tiles' in data and len(data['tiles']) > 0:
                    sortorder = 0
                    with transaction.atomic():
                        for tile in data['tiles']:
                            t = Tile(tile)
                            if t.filter_by_perm(request.user, 'write_nodegroup'):
                                t.sortorder = sortorder
                                t.save(update_fields=['sortorder'], request=request)
                                sortorder = sortorder + 1

                    return JSONResponse(data)

        return HttpResponseNotFound()
Esempio n. 3
0
    def post(self, request):
        if self.action == "update_tile":
            json = request.POST.get("data", None)
            accepted_provisional = request.POST.get("accepted_provisional",
                                                    None)
            if accepted_provisional is not None:
                accepted_provisional_edit = JSONDeserializer().deserialize(
                    accepted_provisional)
            if json is not None:
                data = JSONDeserializer().deserialize(json)
                data[
                    "resourceinstance_id"] = "" if "resourceinstance_id" not in data else data[
                        "resourceinstance_id"]
                if data["resourceinstance_id"] == "":
                    data["resourceinstance_id"] = uuid.uuid4()
                try:
                    models.ResourceInstance.objects.get(
                        pk=data["resourceinstance_id"])
                except ObjectDoesNotExist:
                    try:
                        resource = Resource(
                            uuid.UUID(str(data["resourceinstance_id"])))
                    except ValueError:
                        resource = Resource()
                    graphid = models.Node.objects.filter(
                        nodegroup=data["nodegroup_id"])[0].graph_id
                    resource.graph_id = graphid
                    try:
                        resource.save(user=request.user)
                        data["resourceinstance_id"] = resource.pk
                        resource.index()
                    except ModelInactiveError as e:
                        message = _(
                            "Unable to save. Please verify the model status is active"
                        )
                        return JSONResponse(
                            {
                                "status": "false",
                                "message": [_(e.title),
                                            _(str(message))]
                            },
                            status=500)
                tile_id = data["tileid"]
                resource_instance = models.ResourceInstance.objects.get(
                    pk=data["resourceinstance_id"])
                is_active = resource_instance.graph.isactive
                if tile_id is not None and tile_id != "":
                    try:
                        old_tile = Tile.objects.get(pk=tile_id)
                    except ObjectDoesNotExist as e:
                        return self.handle_save_error(
                            e, _("This tile is no longer available"),
                            _("It was likely deleted by another user"))

                tile = Tile(data)

                if tile.filter_by_perm(
                        request.user, "write_nodegroup") and is_active is True:
                    try:
                        with transaction.atomic():
                            try:
                                if accepted_provisional is None:
                                    try:
                                        tile.save(request=request)
                                    except TileValidationError as e:
                                        resource_tiles = models.TileModel.objects.filter(
                                            resourceinstance=tile.
                                            resourceinstance)
                                        if resource_tiles.count() == 0:
                                            Resource.objects.get(
                                                pk=tile.resourceinstance_id
                                            ).delete(request.user)
                                        title = _(
                                            "Unable to save. Please verify your input is valid"
                                        )
                                        return self.handle_save_error(
                                            e, tile_id, title=title)
                                    except ModelInactiveError as e:
                                        message = _(
                                            "Unable to save. Please verify the model status is active"
                                        )
                                        return JSONResponse(
                                            {
                                                "status":
                                                "false",
                                                "message":
                                                [_(e.title),
                                                 _(str(message))]
                                            },
                                            status=500)
                                else:
                                    if accepted_provisional is not None:
                                        provisional_editor = User.objects.get(
                                            pk=accepted_provisional_edit[
                                                "user"])
                                        prov_edit_log_details = {
                                            "user":
                                            request.user,
                                            "action":
                                            "accept edit",
                                            "edit":
                                            accepted_provisional_edit,
                                            "provisional_editor":
                                            provisional_editor,
                                        }
                                    tile.save(request=request,
                                              provisional_edit_log_details=
                                              prov_edit_log_details)

                                if tile.provisionaledits is not None and str(
                                        request.user.id
                                ) in tile.provisionaledits:
                                    tile.data = tile.provisionaledits[str(
                                        request.user.id)]["value"]

                            except Exception as e:
                                return self.handle_save_error(e, tile_id)

                            tile.after_update_all()
                            update_system_settings_cache(tile)

                    except Exception as e:
                        return self.handle_save_error(e, tile_id)

                    return JSONResponse(tile)
                elif is_active is False:
                    response = {
                        "status":
                        "false",
                        "message": [
                            _("Request Failed"),
                            _("Unable to Save. Verify model status is active")
                        ]
                    }
                    return JSONResponse(response, status=500)
                else:
                    return JSONErrorResponse(_("Request Failed"),
                                             _("Permission Denied"))

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

                if "tiles" in data and len(data["tiles"]) > 0:
                    sortorder = 0
                    with transaction.atomic():
                        for tile in data["tiles"]:
                            t = Tile(tile)
                            if t.filter_by_perm(request.user,
                                                "write_nodegroup"):
                                t.sortorder = sortorder
                                t.save(update_fields=["sortorder"],
                                       request=request)
                                sortorder = sortorder + 1

                    return JSONResponse(data)

        if self.action == "delete_provisional_tile":
            user = request.POST.get("user", None)
            tileid = request.POST.get("tileid", None)
            users = request.POST.get("users", None)
            tile = Tile.objects.get(tileid=tileid)
            is_provisional = tile.is_provisional()

            if tileid is not None and user is not None:
                provisionaledits = self.delete_provisional_edit(
                    tile, user, request)

            elif tileid is not None and users is not None:
                users = jsonparser.loads(users)
                for user in users:
                    self.delete_provisional_edit(tile, user, request)

            if is_provisional == True:
                return JSONResponse({"result": "delete"})
            else:
                return JSONResponse({"result": "success"})

        return HttpResponseNotFound()
Esempio n. 4
0
    def post(self, request):
        if self.action == 'update_tile':
            json = request.POST.get('data', None)
            accepted_provisional = request.POST.get('accepted_provisional',
                                                    None)
            if accepted_provisional is not None:
                accepted_provisional_edit = JSONDeserializer().deserialize(
                    accepted_provisional)
            if json is not None:
                data = JSONDeserializer().deserialize(json)
                data[
                    'resourceinstance_id'] = '' if 'resourceinstance_id' not in data else data[
                        'resourceinstance_id']
                if data['resourceinstance_id'] == '':
                    data['resourceinstance_id'] = uuid.uuid4()
                try:
                    models.ResourceInstance.objects.get(
                        pk=data['resourceinstance_id'])
                except ObjectDoesNotExist:
                    resource = Resource()
                    graphid = models.Node.objects.filter(
                        nodegroup=data['nodegroup_id'])[0].graph_id
                    resource.graph_id = graphid
                    resource.save(user=request.user)
                    data['resourceinstance_id'] = resource.pk
                    resource.index()
                tile_id = data['tileid']
                if tile_id is not None and tile_id != '':
                    try:
                        old_tile = Tile.objects.get(pk=tile_id)
                        clean_resource_cache(old_tile)
                    except ObjectDoesNotExist as e:
                        return self.handle_save_error(
                            e, _('This tile is no longer available'),
                            _('It was likely deleted by another user'))

                tile = Tile(data)

                if tile.filter_by_perm(request.user, 'write_nodegroup'):
                    try:
                        with transaction.atomic():
                            try:
                                if accepted_provisional is None:
                                    try:
                                        tile.save(request=request)
                                    except TileValidationError as e:
                                        resource_tiles = models.TileModel.objects.filter(
                                            resourceinstance=tile.
                                            resourceinstance)
                                        if resource_tiles.count() == 0:
                                            Resource.objects.get(
                                                pk=tile.resourceinstance_id
                                            ).delete(request.user)
                                        title = _(
                                            'Unable to save. Please verify your input is valid'
                                        )
                                        return self.handle_save_error(
                                            e, tile_id, title=title)
                                else:
                                    if accepted_provisional is not None:
                                        provisional_editor = User.objects.get(
                                            pk=accepted_provisional_edit[
                                                "user"])
                                        prov_edit_log_details = {
                                            "user":
                                            request.user,
                                            "action":
                                            "accept edit",
                                            "edit":
                                            accepted_provisional_edit,
                                            "provisional_editor":
                                            provisional_editor
                                        }
                                    tile.save(provisional_edit_log_details=
                                              prov_edit_log_details)

                                if tile.provisionaledits is not None and str(
                                        request.user.id
                                ) in tile.provisionaledits:
                                    tile.data = tile.provisionaledits[str(
                                        request.user.id)]['value']

                            except Exception as e:
                                return self.handle_save_error(e, tile_id)

                            tile.after_update_all()
                            clean_resource_cache(tile)
                            update_system_settings_cache(tile)

                    except Exception as e:
                        return self.handle_save_error(e, tile_id)

                    return JSONResponse(tile)
                else:
                    response = {
                        'status': 'false',
                        'message':
                        [_('Request Failed'),
                         _('Permission Denied')]
                    }
                    return JSONResponse(response, status=500)

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

                if 'tiles' in data and len(data['tiles']) > 0:
                    sortorder = 0
                    with transaction.atomic():
                        for tile in data['tiles']:
                            t = Tile(tile)
                            if t.filter_by_perm(request.user,
                                                'write_nodegroup'):
                                t.sortorder = sortorder
                                t.save(update_fields=['sortorder'],
                                       request=request)
                                sortorder = sortorder + 1

                    return JSONResponse(data)

        if self.action == 'delete_provisional_tile':
            user = request.POST.get('user', None)
            tileid = request.POST.get('tileid', None)
            users = request.POST.get('users', None)
            tile = Tile.objects.get(tileid=tileid)
            is_provisional = tile.is_provisional()

            if tileid is not None and user is not None:
                provisionaledits = self.delete_provisional_edit(
                    tile, user, reviewer=request.user)

            elif tileid is not None and users is not None:
                users = jsonparser.loads(users)
                for user in users:
                    self.delete_provisional_edit(tile,
                                                 user,
                                                 reviewer=request.user)

            if is_provisional == True:
                return JSONResponse({'result': 'delete'})
            else:
                return JSONResponse({'result': 'success'})

        return HttpResponseNotFound()
Esempio n. 5
0
    def post(self, request):
        if self.action == 'update_tile':
            json = request.POST.get('data', None)
            accepted_provisional = request.POST.get('accepted_provisional',
                                                    None)
            if accepted_provisional != None:
                accepted_provisional_edit = JSONDeserializer().deserialize(
                    accepted_provisional)
            if json != None:
                data = JSONDeserializer().deserialize(json)
                if data['resourceinstance_id'] == '':
                    data['resourceinstance_id'] = uuid.uuid4()
                try:
                    models.ResourceInstance.objects.get(
                        pk=data['resourceinstance_id'])
                except ObjectDoesNotExist:
                    resource = Resource()
                    graphid = models.Node.objects.filter(
                        nodegroup=data['nodegroup_id'])[0].graph_id
                    resource.graph_id = graphid
                    resource.save(user=request.user)
                    data['resourceinstance_id'] = resource.pk
                    resource.index()
                tile_id = data['tileid']
                if tile_id != None and tile_id != '':
                    try:
                        old_tile = Tile.objects.get(pk=tile_id)
                        clean_resource_cache(old_tile)
                    except ObjectDoesNotExist:
                        return JSONResponse(
                            {
                                'status':
                                'false',
                                'message': [
                                    _('This tile is no longer available'),
                                    _('It was likely deleted by another user')
                                ]
                            },
                            status=500)
                tile = Tile(data)
                if tile.filter_by_perm(request.user, 'write_nodegroup'):
                    with transaction.atomic():
                        try:
                            if accepted_provisional == None:
                                try:
                                    tile.save(request=request)
                                except TileValidationError as e:
                                    return JSONResponse(
                                        {
                                            'status':
                                            'false',
                                            'message': [
                                                e.message,
                                                _('Unable to Save. Please verify your input is valid'
                                                  )
                                            ]
                                        },
                                        status=500)
                                except Exception as e:
                                    message = "Unable to save. A {0} has occurred. Arguments: {1!r}".format(
                                        type(e).__name__, e.args)
                                    return JSONResponse(
                                        {
                                            'status':
                                            'false',
                                            'message': [
                                                message,
                                                _('Please contact your system administrator'
                                                  )
                                            ]
                                        },
                                        status=500)
                            else:
                                if accepted_provisional is not None:
                                    provisional_editor = User.objects.get(
                                        pk=accepted_provisional_edit["user"])
                                tile.save(
                                    provisional_edit_log_details={
                                        "user": request.user,
                                        "action": "accept edit",
                                        "edit": accepted_provisional_edit,
                                        "provisional_editor":
                                        provisional_editor
                                    })
                            if tile_id == '4345f530-aa90-48cf-b4b3-92d1185ca439':
                                import couchdb
                                import json as json_json
                                couch = couchdb.Server(settings.COUCHDB_URL)
                                for project in models.MobileSurveyModel.objects.all(
                                ):
                                    db = couch['project_' + str(project.id)]
                                    #tile = models.TileModel.objects.get(pk='4345f530-aa90-48cf-b4b3-92d1185ca439')
                                    tile_json = json_json.loads(
                                        JSONSerializer().serialize(tile))
                                    tile_json['_id'] = tile_json['tileid']
                                    for row in db.view('_all_docs',
                                                       include_docs=True):
                                        if 'tileid' in row.doc and tile_json[
                                                '_id'] == row.doc['_id']:
                                            tile_json['_rev'] = row.doc['_rev']
                                            db.save(tile_json)

                            if tile.provisionaledits is not None and str(
                                    request.user.id) in tile.provisionaledits:
                                tile.data = tile.provisionaledits[str(
                                    request.user.id)]['value']

                        except ValidationError as e:
                            return JSONResponse(
                                {
                                    'status': 'false',
                                    'message': e.args
                                },
                                status=500)
                        except Exception as e:
                            exception_title = 'Saving tile failed'
                            exception_message = str(e)
                            if hasattr(e, 'message') and e.message:
                                exception_message += "({0})".format(e.message)

                            logger.error(exception_title +
                                         ''' [Tile id: {tile_id}] \
                                         [Exception message: {message}] \
                                         [Exception trace: {trace}]'''.format(
                                             tile_id=tile_id,
                                             message=exception_message,
                                             trace=traceback.format_exc()))

                            return JSONResponse(
                                {
                                    'status':
                                    'false',
                                    'message': [
                                        _(exception_title),
                                        _(str(exception_message))
                                    ]
                                },
                                status=500)
                        tile.after_update_all()
                        clean_resource_cache(tile)
                        update_system_settings_cache(tile)

                    return JSONResponse(tile)
                else:
                    return JSONResponse(
                        {
                            'status':
                            'false',
                            'message':
                            [_('Request Failed'),
                             _('Permission Denied')]
                        },
                        status=500)

        if self.action == 'reorder_tiles':
            json = request.body
            if json != None:
                data = JSONDeserializer().deserialize(json)

                if 'tiles' in data and len(data['tiles']) > 0:
                    sortorder = 0
                    with transaction.atomic():
                        for tile in data['tiles']:
                            t = Tile(tile)
                            if t.filter_by_perm(request.user,
                                                'write_nodegroup'):
                                t.sortorder = sortorder
                                t.save(update_fields=['sortorder'],
                                       request=request)
                                sortorder = sortorder + 1

                    return JSONResponse(data)

        if self.action == 'delete_provisional_tile':
            user = request.POST.get('user', None)
            tileid = request.POST.get('tileid', None)
            users = request.POST.get('users', None)
            tile = Tile.objects.get(tileid=tileid)
            is_provisional = tile.is_provisional()

            if tileid is not None and user is not None:
                provisionaledits = self.delete_provisional_edit(
                    tile, user, reviewer=request.user)

            elif tileid is not None and users is not None:
                users = jsonparser.loads(users)
                for user in users:
                    self.delete_provisional_edit(tile,
                                                 user,
                                                 reviewer=request.user)

            if is_provisional == True:
                return JSONResponse({'result': 'delete'})
            else:
                return JSONResponse({'result': 'success'})

        return HttpResponseNotFound()
Esempio n. 6
0
    def post(self, request):
        if self.action == 'update_tile':
            json = request.POST.get('data', None)
            if json != None:
                data = JSONDeserializer().deserialize(json)
                try:
                    models.ResourceInstance.objects.get(
                        pk=data['resourceinstance_id'])
                except ObjectDoesNotExist:
                    resource = Resource()
                    resource.resourceinstanceid = data['resourceinstance_id']
                    graphid = models.Node.objects.filter(
                        nodegroup=data['nodegroup_id'])[0].graph_id
                    resource.graph_id = graphid
                    resource.save(user=request.user)
                    resource.index()
                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)
                if tile.filter_by_perm(request.user, 'write_nodegroup'):
                    with transaction.atomic():
                        try:
                            tile.save(request=request)
                            if tile_id == '4345f530-aa90-48cf-b4b3-92d1185ca439':
                                import couchdb
                                import json as json_json
                                couch = couchdb.Server(settings.COUCHDB_URL)
                                for project in models.MobileSurveyModel.objects.all(
                                ):
                                    db = couch['project_' + str(project.id)]
                                    #tile = models.TileModel.objects.get(pk='4345f530-aa90-48cf-b4b3-92d1185ca439')
                                    tile_json = json_json.loads(
                                        JSONSerializer().serialize(tile))
                                    tile_json['_id'] = tile_json['tileid']
                                    for row in db.view('_all_docs',
                                                       include_docs=True):
                                        if 'tileid' in row.doc and tile_json[
                                                '_id'] == row.doc['_id']:
                                            tile_json['_rev'] = row.doc['_rev']
                                            db.save(tile_json)

                        except ValidationError as e:
                            return JSONResponse(
                                {
                                    'status': 'false',
                                    'message': e.args
                                },
                                status=500)
                        tile.after_update_all()
                        clean_resource_cache(tile)
                        update_system_settings_cache(tile)
                    return JSONResponse(tile)
                else:
                    return JSONResponse(
                        {
                            'status':
                            'false',
                            'message':
                            [_('Request Failed'),
                             _('Permission Denied')]
                        },
                        status=500)

        if self.action == 'reorder_tiles':
            json = request.body
            if json != None:
                data = JSONDeserializer().deserialize(json)

                if 'tiles' in data and len(data['tiles']) > 0:
                    sortorder = 0
                    with transaction.atomic():
                        for tile in data['tiles']:
                            t = Tile(tile)
                            if t.filter_by_perm(request.user,
                                                'write_nodegroup'):
                                t.sortorder = sortorder
                                t.save(update_fields=['sortorder'],
                                       request=request)
                                sortorder = sortorder + 1

                    return JSONResponse(data)

        if self.action == 'delete_provisional_tile':
            data = request.POST
            if 'tileid' in data:
                provisionaledits = self.delete_provisional_edit(data, request)
                return JSONResponse(provisionaledits)

            else:
                payload = data.get('payload', None)
                if payload is not None:
                    edits = jsonparser.loads(payload)
                    for edit in edits['edits']:
                        provisionaledits = self.delete_provisional_edit(
                            edit, request)
                return JSONResponse({'result': 'success'})

        return HttpResponseNotFound()
Esempio n. 7
0
    def post(self, request):
        if self.action == 'update_tile':
            json = request.POST.get('data', None)
            if json != None:
                data = JSONDeserializer().deserialize(json)
                try:
                    models.ResourceInstance.objects.get(pk=data['resourceinstance_id'])
                except ObjectDoesNotExist:
                    resource = Resource()
                    resource.resourceinstanceid = data['resourceinstance_id']
                    graphid = models.Node.objects.filter(nodegroup=data['nodegroup_id'])[0].graph_id
                    resource.graph_id = graphid
                    resource.save(user=request.user)
                    resource.index()
                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)
                if tile.filter_by_perm(request.user, 'write_nodegroup'):
                    with transaction.atomic():
                        try:
                            tile.save(request=request)
                            if tile_id == '4345f530-aa90-48cf-b4b3-92d1185ca439':
                                import couchdb
                                import json as json_json
                                couch = couchdb.Server(settings.COUCHDB_URL)
                                for project in models.MobileSurveyModel.objects.all():
                                    db = couch['project_' + str(project.id)]
                                    #tile = models.TileModel.objects.get(pk='4345f530-aa90-48cf-b4b3-92d1185ca439')
                                    tile_json = json_json.loads(JSONSerializer().serialize(tile))
                                    tile_json['_id'] = tile_json['tileid']
                                    for row in db.view('_all_docs', include_docs=True):
                                        if 'tileid' in row.doc and tile_json['_id'] == row.doc['_id']:
                                            tile_json['_rev'] = row.doc['_rev']
                                            db.save(tile_json)

                        except ValidationError as e:
                            return JSONResponse({'status':'false','message':e.args}, status=500)
                        tile.after_update_all()
                        clean_resource_cache(tile)
                        update_system_settings_cache(tile)
                    return JSONResponse(tile)
                else:
                    return JSONResponse({'status':'false','message': [_('Request Failed'), _('Permission Denied')]}, status=500)

        if self.action == 'reorder_tiles':
            json = request.body
            if json != None:
                data = JSONDeserializer().deserialize(json)

                if 'tiles' in data and len(data['tiles']) > 0:
                    sortorder = 0
                    with transaction.atomic():
                        for tile in data['tiles']:
                            t = Tile(tile)
                            if t.filter_by_perm(request.user, 'write_nodegroup'):
                                t.sortorder = sortorder
                                t.save(update_fields=['sortorder'], request=request)
                                sortorder = sortorder + 1

                    return JSONResponse(data)

        if self.action == 'delete_provisional_tile':
            data = request.POST
            if 'tileid' in data:
                provisionaledits = self.delete_provisional_edit(data, request)
                return JSONResponse(provisionaledits)

            else:
                payload = data.get('payload', None)
                if payload is not None:
                    edits = jsonparser.loads(payload)
                    for edit in edits['edits']:
                        provisionaledits = self.delete_provisional_edit(edit, request)
                return JSONResponse({'result':'success'})

        return HttpResponseNotFound()