Gitlab CSE Unil

views.py 10.5 KB
Newer Older
Julien Furrer's avatar
Julien Furrer committed
1
2
3
# coding=utf-8
from __future__ import unicode_literals

Julien Furrer's avatar
Julien Furrer committed
4
5
6
import json
import os
from django.conf import settings
7
from django.core.exceptions import PermissionDenied
Julien Furrer's avatar
Julien Furrer committed
8
9
10
11
12
13
from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, Http404, \
    HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
14
from django.views.decorators.cache import cache_control
Julien Furrer's avatar
Julien Furrer committed
15
16
from PIL import Image
from adim.models import AnObj
17
from adim.models.annotables import AnObjMembership
18
from adim.permissions import check_anobj_permission, get_permission_class, has_anobj_access
Julien Furrer's avatar
Julien Furrer committed
19
20
from .forms import UploadImageFileForm
from sendfile import sendfile
Julien Furrer's avatar
Julien Furrer committed
21
22
from .utils import add_image_border, create_image_thumbnail

Julien Furrer's avatar
Julien Furrer committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

def home(request):
    """
    Home page
    :param request:
    :return:
    """
    context = {}
    if request.user.is_anonymous():
        context['next'] = request.GET.get('next', "")
    return render(request, "adim_app/home.html", context)


def handle_404(request):
    if request.user.is_authenticated():
38
        return HttpResponseRedirect(reverse("adim_app:annotate-new"))
Julien Furrer's avatar
Julien Furrer committed
39
    else:
40
        return HttpResponseRedirect(reverse('adim_app:home'))
Julien Furrer's avatar
Julien Furrer committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63


@login_required()
def essai(request):
    """
    Page d'essais
    :param request:
    :return:
    """
    return render(request, "adim_app/essai.html", {})
    # return render(request, "adim_app/essai.html", {})


@login_required
def _get_anobj(request, anobj_uuid=None, anobj_id=None):
    """
    Returns an AnObj with the uuid or id passed in parameters if
    the request.user has sufficient permissions for it
    Raise a 404 if it cannot return the AnObj

    :param request:
    :param anobj_uuid:
    :return: AnObj
64
    :raise: PermissionDenied
Julien Furrer's avatar
Julien Furrer committed
65
66
67
68
69
70
71
72
73
    """
    q = {}
    if anobj_uuid is not None:
        q['uuid'] = anobj_uuid
    elif anobj_id is not None:
        q['id'] = anobj_id
    if not q:
        raise Http404()
    anobj = get_object_or_404(AnObj, **q)
74
75
76
77

    if not has_anobj_access(request, anobj):
        raise PermissionDenied()

Julien Furrer's avatar
Julien Furrer committed
78
79
80
81
    return anobj


@login_required
82
@cache_control(public=True, max_age=120)
Julien Furrer's avatar
Julien Furrer committed
83
84
85
86
87
88
89
90
def send_anobj_img(request, anobj_uuid):
    try:
        anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
        return sendfile(request, anobj.image.path)
    except Http404:
        return HttpResponseForbidden('Sorry, you cannot access this file')


91
92
93
94
95
96
97
98
@login_required
def anobj_thumb(request, anobj_uuid):
    if request.method == 'GET':
        return send_anobj_thumb(request, anobj_uuid=anobj_uuid)
    elif request.method == 'POST':
        return upload_anobj_thumb(request, anobj_uuid=anobj_uuid)


Julien Furrer's avatar
Julien Furrer committed
99
@login_required
Julien Furrer's avatar
Julien Furrer committed
100
@cache_control(public=True, max_age=1)
Julien Furrer's avatar
Julien Furrer committed
101
102
103
def send_anobj_thumb(request, anobj_uuid):
    try:
        anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
104
        thumb_name = "{name}__{user}.png".format(name=os.path.splitext(anobj.image.name)[0], user=request.user.id)
Julien Furrer's avatar
Julien Furrer committed
105
106
        thumb_path = os.path.join(
            settings.MEDIA_ROOT,
107
            thumb_name
Julien Furrer's avatar
Julien Furrer committed
108
        )
109
110
111
112
113
114
115
116
        # If there is not yet a thumbnail for the current user
        # return the original one
        if not os.path.isfile(thumb_path):
            thumb_name = "{name}__.png".format(name=os.path.splitext(anobj.image.name)[0])
            thumb_path = os.path.join(
                settings.MEDIA_ROOT,
                thumb_name
            )
Julien Furrer's avatar
Julien Furrer committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
        return sendfile(request, thumb_path)
    except Http404:
        return HttpResponseForbidden('Sorry, you cannot access this file')


@login_required
def annotate_new(request):
    return render(request, "adim_app/annotation_new.html", {})


@login_required
def annotate(request, anobj_uuid=None):
    """
    Annotation page
    :param request:
    :param anobj_uuid:
    :return:
    """
    context = {}

137
138
139
140
141
    anobj = get_object_or_404(AnObj, uuid__startswith=anobj_uuid)

    # In case of fragmentary uuid, redirect to the url with full uuid
    if len(anobj_uuid) < 32:
        return HttpResponseRedirect(reverse('adim_app:annotate', kwargs={'anobj_uuid': anobj.uuid}))
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

    # Detailed check for permissions
    if request.user != anobj.owner:
        # User is guest
        perm_class = get_permission_class(anobj.sharing_mode)

        if perm_class is None:
            # AnObj not shared
            raise Http404()
            # raise PermissionDenied()

        elif not perm_class.has_permission(request, anobj):
            # AnObj shared but user has no permission
            if perm_class.has_interactive_registration:
                # Interactive registration exists, call it
                return perm_class.get_interactive_registration_response(request, anobj)

            # No interactive registration
            raise PermissionDenied()

        else:
            # AnObj shared, user registred, go on
            pass

166
167
        context['membership'] = AnObjMembership.objects.get(anobj=anobj, user=request.user)

168
169
170
    if request.method == 'POST':
        return HttpResponseRedirect(reverse('adim_app:annotate', kwargs={'anobj_uuid': anobj_uuid}))

Julien Furrer's avatar
Julien Furrer committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    context.update({
        'anobj': anobj
    })
    return render(request, "adim_app/annotation.html", context)


@login_required
def upload_file(request, anobj_uuid=None):
    """

    -- inspired by: https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/blob/master/upload/views.py
    :param request:
    :return:
    """
    if request.method != 'POST':
        return HttpResponseBadRequest()

    response_type = "application/json"
    response_data = {}

    form = UploadImageFileForm(request.POST, request.FILES)
    if form.is_valid():
        image_file = request.FILES['image_file']
        file_response = _validate_uploaded_file(image_file)
        response_data.update({
            'error': file_response.get('error'),
            'files': [file_response],
        })

        # Create AnObj
        if not file_response['error']:
            try:
                anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
                anobj.image = image_file
                anobj.save()
Julien Furrer's avatar
Julien Furrer committed
206

Julien Furrer's avatar
Julien Furrer committed
207
208
209
210
211
212
            except Http404:
                anobj = AnObj.objects.create(
                    owner=request.user,
                    name=os.path.splitext(image_file.name)[0],
                    image=image_file
                )
Julien Furrer's avatar
Julien Furrer committed
213

214
            # Create original thumbnail, returned to user who has not yet annotated
Julien Furrer's avatar
Julien Furrer committed
215
            create_image_thumbnail(anobj.image.path)
216
            response_data['next'] = reverse('adim_app:annotate', kwargs={'anobj_uuid': anobj.uuid})
Julien Furrer's avatar
Julien Furrer committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261

        # Needed when using iFrame transport
        if "text/html" in request.META["HTTP_ACCEPT"]:
            response_type = "text/html"
    else:
        response_data['error'] = "invalid"

    if request.is_ajax():
        return HttpResponse(json.dumps(response_data), content_type=response_type)
    else:
        return HttpResponseRedirect(response_data['next'])
    

def _validate_uploaded_file(image_file):
    options = {
        # the maximum file size (must be in bytes)
        "maxfilesize": settings.ADIM_UPLOAD_MAX_FILESIZE * 2 ** 20,  # 2 Mb
        # the file types which are going to be allowed for upload
        # must be a mimetype
        "acceptedformats": (
            "image/jpeg",
            "image/jpg",
            "image/png",
        )
    }

    error_id = False
    if image_file.size > options["maxfilesize"]:
        error_id = "maxFileSize"
    # allowed file type
    if image_file.content_type not in options["acceptedformats"]:
        error_id = "acceptFileTypes"

    response_data = {
        "name": image_file.name,
        "size": image_file.size,
        "type": image_file.content_type,
        "error": error_id,
    }

    return response_data


@login_required
@require_POST
262
263
264
265
266
267
268
269
270
def upload_anobj_thumb(request, anobj_uuid=None):
    if anobj_uuid:
        anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
    else:
        try:
            anobj_id = int(request.POST.get('aid'))
            anobj = _get_anobj(request, anobj_id=anobj_id)
        except TypeError:
            return HttpResponseBadRequest()
Julien Furrer's avatar
Julien Furrer committed
271

272
273
    thumb_name = "{name}__{user}.png".format(name=os.path.splitext(anobj.image.name)[0], user=request.user.id)
    # thumb_name = "{name}__.png".format(name=os.path.splitext(anobj.image.name)[0])
Julien Furrer's avatar
Julien Furrer committed
274
    thumb_path = os.path.join(settings.MEDIA_ROOT, thumb_name)
275

Julien Furrer's avatar
Julien Furrer committed
276
    # thumb_url = reverse('adim.app:ao_thumb', kwargs={'anobj_uuid': anobj.uuid})
Julien Furrer's avatar
Julien Furrer committed
277
278
279
280
281
282
283
284
285
286

    thumb_file = request.FILES['file']
    response_data = _validate_uploaded_file(thumb_file)
    if response_data['error']:
        return HttpResponseBadRequest()

    with open(thumb_path, 'wb+') as destination:
        for chunk in thumb_file.chunks():
            destination.write(chunk)

Julien Furrer's avatar
Julien Furrer committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    add_image_border(thumb_path, save=True)
    # add_borders(thumb_path)

    # if anobj.thumb_url != thumb_url:
    #     anobj.thumb_url = thumb_url
    #     anobj.save()

    return HttpResponse()
    # return HttpResponse(anobj.thumb_url, content_type="text/plain")


# def add_borders(thumb_path):
#     brd_w = 1
#
#     thumb_image = Image.open(thumb_path)
#     overlay_image = Image.new(thumb_image.mode, thumb_image.size, color=(0, 0, 0))
#     result_image = Image.blend(thumb_image, overlay_image, alpha=0.33)
#     result_image.paste(
#         thumb_image.crop(
#             (brd_w, brd_w) + tuple(a - brd_w for a in thumb_image.size)
#         ),
#         box=(brd_w, brd_w)
#     )
#     result_image.save(thumb_path)


# def add_borders2(img, save=False):
#     if type(img) == str or type(img) == unicode:
#         try:
#             thumb_image = Image.open(img)
#             thumb_path = img
#         except IOError:
#             # TODO: log some error
#             return
#     elif Image.isImageType(img):
#         thumb_image = img
#         thumb_path = img.filename
#     else:
#         raise TypeError()
#
#     brd_w = 1
#
#     overlay_image = Image.new(thumb_image.mode, thumb_image.size, color=(0, 0, 0))
#     result_image = Image.blend(thumb_image, overlay_image, alpha=0.33)
#     result_image.paste(
#         thumb_image.crop(
#             (brd_w, brd_w) + tuple(a - brd_w for a in thumb_image.size)
#         ),
#         box=(brd_w, brd_w)
#     )
#     if save:
#         result_image.save(thumb_path)
#     return result_image
Julien Furrer's avatar
Julien Furrer committed
340
341
342
343
344
345
346


def _handle_uploaded_file(image_file, destination):
    destination_path = os.path.join(settings.MEDIA_ROOT, destination, image_file.name)
    with open(destination_path, 'wb+') as destination:
        for chunk in image_file.chunks():
            destination.write(chunk)