217a78b59ae983798378a54b636abf15e1142708
[redakcja.git] / apps / fileupload / views.py
1 import json
2 import os
3 from .forms import UploadForm
4 from django.views.generic import FormView, View
5 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404
6 from django.conf import settings
7
8
9 class JSONResponse(HttpResponse):
10     """JSON response class."""
11     def __init__(self, obj='', mimetype="application/json", *args, **kwargs):
12         content = json.dumps(obj)
13         super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
14
15 class UploadView(FormView):
16     template_name = "fileupload/picture_form.html"
17     form_class = UploadForm
18
19     def get_safe_path(self, filename=""):
20         path = os.path.abspath(os.path.join(
21                 settings.MEDIA_ROOT,
22                 self.get_directory(),
23                 filename))
24         if not path.startswith(settings.MEDIA_ROOT):
25             raise Http404
26         if filename:
27             if not path.startswith(self.get_safe_path()):
28                 raise Http404
29         return path
30
31     def get_url(self, filename=""):
32         return settings.MEDIA_URL + self.get_directory() + filename
33
34     def dispatch(self, request, *args, **kwargs):
35         self.object = self.get_object(request, *args, **kwargs)
36         return super(UploadView, self).dispatch(request, *args, **kwargs)
37
38     def get(self, request, *args, **kwargs):
39         if request.is_ajax():
40             files = []
41             
42             path = self.get_safe_path()
43             if os.path.isdir(path):
44                 for f in os.listdir(path):
45                     files.append({
46                         "name": f,
47                         "url": self.get_url(f),
48                         'thumbnail_url': self.get_url(f), # FIXME: thumb!
49                         'delete_url': "%s?file=%s" % (request.get_full_path(), f), # FIXME: encode
50                         'delete_type': "DELETE"
51                     })
52             return JSONResponse(files)
53         else:
54             return super(UploadView, self).get(request, *args, **kwargs)
55
56     def form_valid(self, form):
57         f = self.request.FILES.get('file')
58         path = self.get_safe_path()
59         
60         if not os.path.isdir(path):
61             os.makedirs(path)
62         with open(self.get_safe_path(f.name), 'w') as destination:
63             for chunk in f.chunks():
64                 destination.write(chunk)
65         data = [{
66             'name': f.name, 
67             'url': self.get_url(f.name),
68             'thumbnail_url': self.get_url(f.name), # FIXME: thumb!
69             'delete_url': "%s?file=%s" % (self.request.get_full_path(), f.name), # FIXME: encode
70             'delete_type': "DELETE"
71         }]
72         response = JSONResponse(data)
73         response['Content-Disposition'] = 'inline; filename=files.json'
74         return response
75
76     def delete(self, request, *args, **kwargs):
77         os.unlink(self.get_safe_path(request.GET.get('file')))
78         response = JSONResponse(True)
79         response['Content-Disposition'] = 'inline; filename=files.json'
80         return response