3 from urllib import quote
4 from django.conf import settings
5 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404
6 from django.utils.decorators import method_decorator
7 from django.views.decorators.vary import vary_on_headers
8 from django.views.generic import FormView, View
9 from .forms import UploadForm
12 # Use sorl.thumbnail if available.
14 from sorl.thumbnail import default
16 def thumbnail(relpath):
17 return settings.MEDIA_URL + relpath
19 def thumbnail(relpath):
21 return default.backend.get_thumbnail(relpath, "x50").url
23 # That's not an image. No thumb.
27 class JSONResponse(HttpResponse):
28 """JSON response class."""
29 def __init__(self, obj='', mimetype="application/json", *args, **kwargs):
30 content = json.dumps(obj)
31 super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
34 class UploadView(FormView):
35 template_name = "fileupload/picture_form.html"
36 form_class = UploadForm
38 def get_object(self, request, *args, **kwargs):
39 """Get any data for later use."""
42 def get_directory(self):
43 """Directory relative to MEDIA_ROOT. Must end with a slash."""
44 return self.kwargs['path']
46 def breadcrumbs(self):
47 """List of tuples (name, url) or just (name,) for breadcrumbs.
49 Probably only the last item (representing currently browsed dir)
53 directory = self.get_directory()
54 now_path = os.path.dirname(self.request.get_full_path())
55 directory = os.path.dirname(directory)
58 (os.path.basename(directory),)
60 directory = os.path.dirname(directory)
61 now_path = (os.path.dirname(now_path))
63 crumbs.insert(0, (os.path.basename(directory), now_path+'/'))
64 directory = os.path.dirname(directory)
65 now_path = os.path.dirname(now_path)
66 crumbs.insert(0, ('media', now_path))
71 def get_safe_path(self, filename=""):
72 """Finds absolute filesystem path of the browsed dir of file.
74 Makes sure it's inside MEDIA_ROOT.
77 path = os.path.abspath(os.path.join(
81 if not path.startswith(settings.MEDIA_ROOT):
84 if not path.startswith(self.get_safe_path()):
88 def get_url(self, filename):
89 """Finds URL of a file in browsed dir."""
90 return settings.MEDIA_URL + self.get_directory() + quote(filename.encode('utf-8'))
92 @method_decorator(vary_on_headers('Accept'))
93 def dispatch(self, request, *args, **kwargs):
94 self.object = self.get_object(request, *args, **kwargs)
95 return super(UploadView, self).dispatch(request, *args, **kwargs)
97 def get(self, request, *args, **kwargs):
100 path = self.get_safe_path()
101 if os.path.isdir(path):
102 for f in os.listdir(path):
106 if os.path.isdir(os.path.join(path, f)):
108 "url": "%s%s/" % (request.get_full_path(), f),
112 "url": self.get_url(f),
113 'thumbnail_url': thumbnail(self.get_directory() + f),
114 'delete_url': "%s?file=%s" % (
115 request.get_full_path(),
116 quote(f.encode('utf-8'))),
117 'delete_type': "DELETE"
119 thumbnail_url = thumbnail(self.get_directory() + f),
120 files.append(file_info)
121 return JSONResponse(files)
123 return super(UploadView, self).get(request, *args, **kwargs)
125 def form_valid(self, form):
126 flist = self.request.FILES.getlist('files')
127 path = self.get_safe_path()
128 if not os.path.isdir(path):
132 with open(self.get_safe_path(f.name), 'w') as destination:
133 for chunk in f.chunks():
134 destination.write(chunk)
137 'url': self.get_url(f.name),
138 'thumbnail_url': thumbnail(self.get_directory() + f.name),
139 'delete_url': "%s?file=%s" % (
140 request.get_full_path(),
141 quote(f.name.encode('utf-8'))),
142 'delete_type': "DELETE"
144 response = JSONResponse(data)
145 response['Content-Disposition'] = 'inline; filename=files.json'
148 def delete(self, request, *args, **kwargs):
149 os.unlink(self.get_safe_path(request.GET.get('file')))
150 response = JSONResponse(True)
151 response['Content-Disposition'] = 'inline; filename=files.json'