Ejemplo n.º 1
0
def save_editorial(request, graphs):
    if settings.ARCHETYPE_API_READ_ONLY:
        #        transaction.rollback()
        raise Http404
    else:
        data = {'success': False, 'graphs': []}

        if not graphs or len(graphs) == 0:
            raise Exception('No data provided')

        try:
            graphs = graphs.replace('/"', "'")
            graphs = json.loads(graphs)
            for gr in graphs:
                image = Image.objects.get(id=gr['image'])
                get_data = request.POST.copy()
                _id = gr['id']
                count = 0
                if _id and _id.isdigit():
                    count = Annotation.objects.filter(image=image,
                                                      id=_id).count()
                if 'geoJson' in gr:
                    geo_json = str(gr['geoJson'])
                else:
                    geo_json = False

                if count > 0:
                    annotation = Annotation.objects.get(image=image, id=_id)
                else:
                    annotation = Annotation(image=image, type='editorial')

                form = ImageAnnotationForm(data=get_data)
                if form.is_valid():
                    with transaction.atomic():
                        clean = form.cleaned_data

                        if geo_json:
                            annotation.geo_json = geo_json

                        # set the note (only if different) - see JIRA
                        # DIGIPAL-477
                        for f in ['display_note', 'internal_note']:

                            if getattr(annotation,
                                       f) != clean[f] and f in get_data:
                                setattr(annotation, f, clean[f])

                        if not annotation.id:
                            # set the author only when the annotation is
                            # created
                            annotation.author = request.user

                        if geo_json:
                            annotation.set_graph_group()
                        annotation.save()

                        new_graph = [{}]

                        if 'vector_id' in gr:
                            new_graph[0]['vector_id'] = gr['vector_id']
                        new_graph[0]['annotation_id'] = unicode(annotation.id)
                        if has_edit_permission(request, Annotation):
                            new_graph[0][
                                'internal_note'] = annotation.internal_note
                        new_graph[0]['display_note'] = annotation.display_note

                        data['graphs'].append(new_graph[0])

                        # transaction.commit()
                        data['success'] = True

        # uncomment this to see the error call stack in the django server output
        # except ValueError as e:
        except Exception as e:
            data['success'] = False
            data['errors'] = [u'Internal error: %s' % e]
            # tb = sys.exc_info()[2]

        return HttpResponse(json.dumps(data), content_type='application/json')
Ejemplo n.º 2
0
def save(request, graphs):
    """Saves an annotation and creates a cutout of the annotation."""

    if settings.ARCHETYPE_API_READ_ONLY:
        #        transaction.rollback()
        raise Http404
    else:

        data = {'success': False, 'graphs': []}

        try:

            graphs = graphs.replace('/"', "'")
            graphs = json.loads(graphs)

            for gr in graphs:
                graph_object = False

                if 'id' in gr:
                    graph_object = Graph.objects.get(id=gr['id'])

                image = Image.objects.get(id=gr['image'])
                annotation_is_modified = False
                if graph_object:
                    annotation = graph_object.annotation
                    graph = graph_object
                else:
                    graph = Graph()
                    annotation = Annotation(image=image)

                get_data = request.POST.copy()

                if 'geoJson' in gr:
                    geo_json = str(gr['geoJson'])
                else:
                    geo_json = False

                form = ImageAnnotationForm(data=get_data)
                if form.is_valid():
                    with transaction.atomic():
                        clean = form.cleaned_data
                        if geo_json:
                            annotation.geo_json = geo_json
                            annotation_is_modified = True
                        # set the note (only if different) - see JIRA
                        # DIGIPAL-477
                        for f in ['display_note', 'internal_note']:
                            if getattr(annotation, f) != clean[f]:
                                setattr(annotation, f, clean[f])
                                annotation_is_modified = True
                        if not annotation.id:
                            # set the author only when the annotation is
                            # created
                            annotation.author = request.user
                        # annotation.before = clean['before']
                        # annotation.after = clean['after']
                        allograph = clean['allograph']
                        hand = clean['hand']

                        if hand and allograph:

                            scribe = hand.scribe

                            # GN: if this is a new Graph, it has no idiograph
                            # yet, so we test this first
                            if graph.id and (allograph.id !=
                                             graph.idiograph.allograph.id):
                                graph.graph_components.all().delete()

                            idiograph_list = Idiograph.objects.filter(
                                allograph=allograph, scribe=scribe)

                            if idiograph_list:
                                idiograph = idiograph_list[0]
                                idiograph.id
                            else:
                                idiograph = Idiograph(allograph=allograph,
                                                      scribe=scribe)
                                idiograph.save()

                            graph.idiograph = idiograph
                            graph.hand = hand

                            graph.save()  # error is here
                        feature_list_checked = get_data.getlist('feature')

                        feature_list_unchecked = get_data.getlist('-feature')

                        if feature_list_unchecked:

                            for value in feature_list_unchecked:

                                cid, fid = value.split('::')

                                component = Component.objects.get(id=cid)
                                feature = Feature.objects.get(id=fid)
                                gc_list = GraphComponent.objects.filter(
                                    graph=graph, component=component)

                                if gc_list:
                                    gc = gc_list[0]
                                    gc.features.remove(feature)
                                    gc.save()

                                    if not gc.features.all():
                                        gc.delete()

                        if feature_list_checked:

                            for value in feature_list_checked:
                                cid, fid = value.split('::')

                                component = Component.objects.get(id=cid)
                                feature = Feature.objects.get(id=fid)
                                gc_list = GraphComponent.objects.filter(
                                    graph=graph, component=component)

                                if gc_list:
                                    gc = gc_list[0]
                                else:
                                    gc = GraphComponent(graph=graph,
                                                        component=component)
                                    gc.save()

                                gc.features.add(feature)
                                gc.save()

                        aspects = get_data.getlist('aspect')
                        aspects_deleted = get_data.getlist('-aspect')

                        if aspects:
                            for aspect in aspects:
                                aspect_model = Aspect.objects.get(id=aspect)
                                graph.aspects.add(aspect_model)

                        if aspects_deleted:
                            for aspect in aspects_deleted:
                                aspect_model = Aspect.objects.get(id=aspect)
                                graph.aspects.remove(aspect_model)

                        graph.save()

                        # Only save the annotation if it has been modified (or new one)
                        # see JIRA DIGIPAL-477
                        if annotation_is_modified or not annotation.id:
                            annotation.graph = graph
                            annotation.save()
                            # attach the graph to a containing one
                            # cannot be called BEFORE saving the
                            # annotation/graph
                            if geo_json:
                                annotation.set_graph_group()

                        new_graph = json.loads(get_features(graph.id))
                        if 'vector_id' in gr:
                            new_graph[0]['vector_id'] = gr['vector_id']

                        if has_edit_permission(request, Annotation):
                            new_graph[0][
                                'internal_note'] = annotation.internal_note
                        new_graph[0]['display_note'] = annotation.display_note

                        data['graphs'].append(new_graph[0])

                        # transaction.commit()
                        data['success'] = True
                else:
                    # transaction.rollback()
                    data['success'] = False
                    data['errors'] = get_json_error_from_form_errors(form)

        # uncomment this to see the error call stack in the django server output
        # except ValueError as e:
        except Exception as e:
            data['success'] = False
            data['errors'] = [u'Internal error: %s' % e]
            # tb = sys.exc_info()[2]

        return HttpResponse(json.dumps(data), content_type='application/json')
Ejemplo n.º 3
0
def save_editorial(request, graphs):
    if settings.REJECT_HTTP_API_REQUESTS:
#        transaction.rollback()
        raise Http404
    else:
        data = {
            'success': False,
            'graphs': []
        }

        if not graphs or len(graphs) == 0:
            raise Exception('No data provided')

        try:
            graphs = graphs.replace('/"', "'")
            graphs = json.loads(graphs)
            for gr in graphs:
                image = Image.objects.get(id=gr['image'])
                get_data = request.POST.copy()
                _id = gr['id']
                count = 0
                if _id and _id.isdigit():
                    count = Annotation.objects.filter(image=image, id=_id).count()
                if 'geoJson' in gr:
                    geo_json = str(gr['geoJson'])
                else:
                    geo_json = False

                if count > 0:
                    annotation = Annotation.objects.get(image=image, id=_id)
                else:
                    annotation = Annotation(image=image, type='editorial')

                form = ImageAnnotationForm(data=get_data)
                if form.is_valid():
                    with transaction.atomic():
                        clean = form.cleaned_data

                        if geo_json:
                            annotation.geo_json = geo_json

                        # set the note (only if different) - see JIRA DIGIPAL-477
                        for f in ['display_note', 'internal_note']:

                            if getattr(annotation, f) != clean[f] and f in get_data:
                                setattr(annotation, f, clean[f])

                        if not annotation.id:
                            # set the author only when the annotation is created
                            annotation.author = request.user

                        if geo_json:
                            annotation.set_graph_group()
                        annotation.save()

                        new_graph = [{}]

                        if 'vector_id' in gr:
                            new_graph[0]['vector_id'] = gr['vector_id']
                        new_graph[0]['annotation_id'] = unicode(annotation.id)
                        if has_edit_permission(request, Annotation):
                            new_graph[0]['internal_note'] = annotation.internal_note
                        new_graph[0]['display_note'] = annotation.display_note

                        data['graphs'].append(new_graph[0])

                        #transaction.commit()
                        data['success'] = True

        # uncomment this to see the error call stack in the django server output
        #except ValueError as e:
        except Exception as e:
            data['success'] = False
            data['errors'] = [u'Internal error: %s' % e]
            #tb = sys.exc_info()[2]

        return HttpResponse(json.dumps(data), content_type='application/json')
Ejemplo n.º 4
0
def save(request, graphs):

    """Saves an annotation and creates a cutout of the annotation."""

    if settings.REJECT_HTTP_API_REQUESTS:
#        transaction.rollback()
        raise Http404
    else:

        data = {
            'success': False,
            'graphs': []
        }

        try:

            graphs = graphs.replace('/"', "'")
            graphs = json.loads(graphs)

            for gr in graphs:
                graph_object = False

                if 'id' in gr:
                    graph_object = Graph.objects.get(id=gr['id'])

                image = Image.objects.get(id=gr['image'])
                annotation_is_modified = False
                if graph_object:
                    annotation = graph_object.annotation
                    graph = graph_object
                else:
                    graph = Graph()
                    annotation = Annotation(image=image)

                get_data = request.POST.copy()

                if 'geoJson' in gr:
                    geo_json = str(gr['geoJson'])
                else:
                    geo_json = False


                form = ImageAnnotationForm(data=get_data)
                if form.is_valid():
                    with transaction.atomic():
                        clean = form.cleaned_data
                        if geo_json:
                            annotation.geo_json = geo_json
                            annotation_is_modified = True
                        # set the note (only if different) - see JIRA DIGIPAL-477
                        for f in ['display_note', 'internal_note']:
                            if getattr(annotation, f) != clean[f]:
                                setattr(annotation, f, clean[f])
                                annotation_is_modified = True
                        if not annotation.id:
                            # set the author only when the annotation is created
                            annotation.author = request.user
                        #annotation.before = clean['before']
                        #annotation.after = clean['after']
                        allograph = clean['allograph']
                        hand = clean['hand']

                        if hand and allograph:

                            scribe = hand.scribe

                            # GN: if this is a new Graph, it has no idiograph yet, so we test this first
                            if graph.id and (allograph.id != graph.idiograph.allograph.id):
                                graph.graph_components.all().delete()

                            idiograph_list = Idiograph.objects.filter(allograph=allograph,
                                    scribe=scribe)

                            if idiograph_list:
                                idiograph = idiograph_list[0]
                                idiograph.id
                            else:
                                idiograph = Idiograph(allograph=allograph, scribe=scribe)
                                idiograph.save()

                            graph.idiograph = idiograph
                            graph.hand = hand

                            graph.save() # error is here
                        feature_list_checked = get_data.getlist('feature')

                        feature_list_unchecked = get_data.getlist('-feature')

                        if feature_list_unchecked:

                            for value in feature_list_unchecked:

                                cid, fid = value.split('::')

                                component = Component.objects.get(id=cid)
                                feature = Feature.objects.get(id=fid)
                                gc_list = GraphComponent.objects.filter(graph=graph,
                                        component=component)

                                if gc_list:
                                    gc = gc_list[0]
                                    gc.features.remove(feature)
                                    gc.save()

                                    if not gc.features.all():
                                        gc.delete()

                        if feature_list_checked:

                            for value in feature_list_checked:
                                cid, fid = value.split('::')

                                component = Component.objects.get(id=cid)
                                feature = Feature.objects.get(id=fid)
                                gc_list = GraphComponent.objects.filter(graph=graph,
                                        component=component)

                                if gc_list:
                                    gc = gc_list[0]
                                else:
                                    gc = GraphComponent(graph=graph, component=component)
                                    gc.save()

                                gc.features.add(feature)
                                gc.save()

                        aspects = get_data.getlist('aspect')
                        aspects_deleted = get_data.getlist('-aspect')

                        if aspects:
                            for aspect in aspects:
                                aspect_model = Aspect.objects.get(id=aspect)
                                graph.aspects.add(aspect_model)

                        if aspects_deleted:
                            for aspect in aspects_deleted:
                                aspect_model = Aspect.objects.get(id=aspect)
                                graph.aspects.remove(aspect_model)

                        graph.save()

                        # Only save the annotation if it has been modified (or new one)
                        # see JIRA DIGIPAL-477
                        if annotation_is_modified or not annotation.id:
                            annotation.graph = graph
                            annotation.save()
                            # attach the graph to a containing one
                            # cannot be called BEFORE saving the annotation/graph
                            if geo_json:
                                annotation.set_graph_group()

                        new_graph = json.loads(get_features(graph.id))
                        if 'vector_id' in gr:
                            new_graph[0]['vector_id'] = gr['vector_id']

                        if has_edit_permission(request, Annotation):
                            new_graph[0]['internal_note'] = annotation.internal_note
                        new_graph[0]['display_note'] = annotation.display_note

                        data['graphs'].append(new_graph[0])

                        #transaction.commit()
                        data['success'] = True
                else:
                    #transaction.rollback()
                    data['success'] = False
                    data['errors'] = get_json_error_from_form_errors(form)

        # uncomment this to see the error call stack in the django server output
        #except ValueError as e:
        except Exception as e:
            data['success'] = False
            data['errors'] = [u'Internal error: %s' % e]
            #tb = sys.exc_info()[2]

        return HttpResponse(json.dumps(data), content_type='application/json')
Ejemplo n.º 5
0
def update_text_image_link(request, image, ret):
    if ret is None:
        ret = {}
    ret['newids'] = {}

    from digipal.models import has_edit_permission, Annotation
    if not has_edit_permission(request, Annotation):
        set_message(ret, 'Insufficient rights to edit annotations', 'error')
        return ret

    # print 'TEXT IMAGE LINK: image #%s' % image.id
    links = dputils.get_request_var(request, 'links', None)
    if links:
        ''' links = [
                        [
                            [["", "clause"], ["type", "address"]],
                            {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[270,-1632],[270,-984],[3006,-984],[3006,-1632],[270,-1632]]]},"properties":null}
                        ],
                        [...]
                    ]
        '''
        for link in json.loads(links):
            # print link
            attrs, geojson = link[0], link[1]
            clientid = (geojson.get('properties', {})
                        or {}).pop('clientid', '')
            serverid = geojson.pop('id', None)
            action = geojson.pop('action', 'update')

            # 1. find the annotation
            if not clientid and not serverid:
                raise Exception(
                    'Cannot find annotation, need either "id" or "clientid"')

            filter = {}
            if serverid:
                filter['id'] = serverid
            else:
                filter['clientid'] = clientid
            annotation = Annotation.objects.filter(**filter).first()

            # 2. delete or create annotation
            if action == 'deleted':
                if annotation:
                    # print 'delete annotation'
                    annotation.delete()
                    annotation = None
            else:
                # create annotation
                if not annotation:
                    if serverid:
                        raise Exception(
                            'Cannot find annotation by server id %s' % serverid)
                    # print 'create annotation'
                    author = request.user
                    annotation = Annotation(
                        clientid=clientid, image=image, author=author, type='text')

                # update annotation and link
                # print 'update annotation'
                annotation.set_geo_json_from_dict(geojson)
                annotation.save()
                if not serverid:
                    ret['newids'][clientid] = annotation.id

                # update the text-annotation
                from digipal_text.models import TextAnnotation
                # text_annotation = TextAnnotation(annotation=annotation, element=json.dumps(attrs))
                # TODO: assume a single element per annotation for the moment
                text_annotation = TextAnnotation.objects.filter(
                    annotation=annotation).first()
                if not attrs:
                    # delete it
                    if text_annotation:
                        # print 'delete link'
                        text_annotation.delete()
                else:
                    if not text_annotation:
                        # print 'create link'
                        text_annotation = TextAnnotation(annotation=annotation)
                    # print 'update link'
                    text_annotation.elementid = json.dumps(attrs)
                    text_annotation.save()

    return ret
Ejemplo n.º 6
0
def update_text_image_link(request, image, ret):
    if ret is None:
        ret = {}
    ret['newids'] = {}

    from digipal.models import has_edit_permission, Annotation
    if not has_edit_permission(request, Annotation):
        set_message(ret, 'Insufficient rights to edit annotations', 'error')
        return ret

    # print 'TEXT IMAGE LINK: image #%s' % image.id
    links = dputils.get_request_var(request, 'links', None)
    if links:
        ''' links = [
                        [
                            [["", "clause"], ["type", "address"]],
                            {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[270,-1632],[270,-984],[3006,-984],[3006,-1632],[270,-1632]]]},"properties":null}
                        ],
                        [...]
                    ]
        '''
        for link in json.loads(links):
            # print link
            attrs, geojson = link[0], link[1]
            clientid = (geojson.get('properties', {})
                        or {}).pop('clientid', '')
            serverid = geojson.pop('id', None)
            action = geojson.pop('action', 'update')

            # 1. find the annotation
            if not clientid and not serverid:
                raise Exception(
                    'Cannot find annotation, need either "id" or "clientid"')

            filter = {}
            if serverid:
                filter['id'] = serverid
            else:
                filter['clientid'] = clientid
            annotation = Annotation.objects.filter(**filter).first()

            # 2. delete or create annotation
            if action == 'deleted':
                if annotation:
                    # print 'delete annotation'
                    annotation.delete()
                    annotation = None
            else:
                # create annotation
                if not annotation:
                    if serverid:
                        raise Exception(
                            'Cannot find annotation by server id %s' %
                            serverid)
                    # print 'create annotation'
                    author = request.user
                    annotation = Annotation(clientid=clientid,
                                            image=image,
                                            author=author,
                                            type='text')

                # update annotation and link
                # print 'update annotation'
                annotation.set_geo_json_from_dict(geojson)
                annotation.save()
                if not serverid:
                    ret['newids'][clientid] = annotation.id

                # update the text-annotation
                from digipal_text.models import TextAnnotation
                # text_annotation = TextAnnotation(annotation=annotation, element=json.dumps(attrs))
                # TODO: assume a single element per annotation for the moment
                text_annotation = TextAnnotation.objects.filter(
                    annotation=annotation).first()
                if not attrs:
                    # delete it
                    if text_annotation:
                        # print 'delete link'
                        text_annotation.delete()
                else:
                    if not text_annotation:
                        # print 'create link'
                        text_annotation = TextAnnotation(annotation=annotation)
                    # print 'update link'
                    text_annotation.elementid = json.dumps(attrs)
                    text_annotation.save()

    return ret