Esempio n. 1
0
def new_map_json(request):

    if request.method == 'GET':
        config = new_map_config(request)
        if isinstance(config, HttpResponse):
            return config
        else:
            return HttpResponse(config)

    elif request.method == 'POST':
        if not request.user.is_authenticated():
            return HttpResponse(
                'You must be logged in to save new maps',
                content_type="text/plain",
                status=401
            )
        data = json.loads(request.body)
        title = data['about']['title']
        category_id = int(data['about']['category'])
        organization_id = int(data['about']['organization'])
        group = GroupProfile.objects.get(id=organization_id)


        map_obj = Map(owner=request.user, zoom=0,
                      center_x=0, center_y=0,
                      category=TopicCategory.objects.get(id=category_id), group=group, title=title)
        map_obj.save()
        map_obj.set_default_permissions()

        permissions = _perms_info_json(map_obj)
        perm_dict = json.loads(permissions)
        if 'download_resourcebase' in perm_dict['groups']['anonymous']:
            perm_dict['groups']['anonymous'].remove('download_resourcebase')
        if 'view_resourcebase' in perm_dict['groups']['anonymous']:
            perm_dict['groups']['anonymous'].remove('view_resourcebase')
        #
        map_obj.set_permissions(perm_dict)

        # If the body has been read already, use an empty string.
        # See https://github.com/django/django/commit/58d555caf527d6f1bdfeab14527484e4cca68648
        # for a better exception to catch when we move to Django 1.7.
        try:
            body = request.body
        except Exception:
            body = ''

        try:
            map_obj.update_from_viewer(body)

            # notify layer owners that this layer is used to create this map
            layers = map_obj.layers
            layer_owners = [layer.owner for layer in map_obj.local_layers]
            notify.send(request.user, recipient_list=layer_owners, actor=request.user,
                verb='created map using your layer', target=map_obj)

            MapSnapshot.objects.create(
                config=clean_config(body),
                map=map_obj,
                user=request.user)
        except ValueError as e:
            return HttpResponse(str(e), status=400)
        else:
            return HttpResponse(
                json.dumps({'id': map_obj.id}),
                status=200,
                content_type='application/json'
            )
    else:
        return HttpResponse(status=405)