Sith/core/views/files.py

212 lines
8.8 KiB
Python
Raw Normal View History

2016-08-10 03:48:06 +00:00
# This file contains all the views that concern the page model
from django.shortcuts import render, redirect, get_object_or_404
2016-11-09 08:13:57 +00:00
from django.views.generic import ListView, DetailView, TemplateView
2016-08-10 03:48:06 +00:00
from django.views.generic.edit import UpdateView, CreateView, FormMixin, DeleteView
2016-11-09 08:13:57 +00:00
from django.views.generic.detail import SingleObjectMixin
2016-08-10 03:48:06 +00:00
from django.contrib.auth.decorators import login_required, permission_required
from django.forms.models import modelform_factory
from django.forms import CheckboxSelectMultiple
from django.conf import settings
from django.utils.translation import ugettext as _
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django import forms
import os
2016-12-08 18:47:28 +00:00
from core.models import SithFile, RealGroup, Notification
2016-08-10 03:48:06 +00:00
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin, can_view, not_found
2016-11-20 10:56:33 +00:00
def send_file(request, file_id, file_class=SithFile, file_attr="file"):
2016-08-10 03:48:06 +00:00
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
2016-10-26 17:21:19 +00:00
f = file_class.objects.filter(id=file_id).first()
2016-11-30 08:28:22 +00:00
if f is None or not f.file:
2016-08-10 03:48:06 +00:00
return not_found(request)
from counter.models import Counter
if not (can_view(f, request.user) or
('counter_token' in request.session.keys() and
request.session['counter_token'] and # check if not null for counters that have no token set
Counter.objects.filter(token=request.session['counter_token']).exists())
):
2016-08-10 03:48:06 +00:00
raise PermissionDenied
2016-11-20 10:56:33 +00:00
name = f.__getattribute__(file_attr).name
2016-11-25 17:59:22 +00:00
with open((settings.MEDIA_ROOT + name).encode('utf-8'), 'rb') as filename:
2016-08-10 03:48:06 +00:00
wrapper = FileWrapper(filename)
response = HttpResponse(wrapper, content_type=f.mime_type)
2016-11-25 17:59:22 +00:00
response['Content-Length'] = os.path.getsize((settings.MEDIA_ROOT + name).encode('utf-8'))
response['Content-Disposition'] = ('inline; filename="%s"' % f.name).encode('utf-8')
2016-08-10 03:48:06 +00:00
return response
class AddFilesForm(forms.Form):
2016-08-10 03:48:06 +00:00
folder_name = forms.CharField(label=_("Add a new folder"), max_length=30, required=False)
file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), label=_("Files"),
required=False)
def process(self, parent, owner, files):
2016-12-08 18:47:28 +00:00
notif = False
2016-08-10 03:48:06 +00:00
try:
if self.cleaned_data['folder_name'] != "":
folder = SithFile(parent=parent, name=self.cleaned_data['folder_name'], owner=owner)
folder.clean()
folder.save()
2016-12-08 18:47:28 +00:00
notif = True
2016-08-10 03:48:06 +00:00
except Exception as e:
self.add_error(None, _("Error creating folder %(folder_name)s: %(msg)s") %
{'folder_name': self.cleaned_data['folder_name'], 'msg': str(e.message)})
for f in files:
new_file = SithFile(parent=parent, name=f.name, file=f, owner=owner, is_folder=False,
mime_type=f.content_type, size=f._size)
try:
new_file.clean()
new_file.save()
2016-12-08 18:47:28 +00:00
notif = True
2016-08-10 03:48:06 +00:00
except Exception as e:
2016-08-31 00:05:04 +00:00
self.add_error(None, _("Error uploading file %(file_name)s: %(msg)s") % {'file_name': f, 'msg': repr(e)})
2016-12-08 18:47:28 +00:00
if notif:
for u in RealGroup.objects.filter(id=settings.SITH_SAS_ADMIN_GROUP_ID).first().users.all():
if not u.notifications.filter(type="FILE_MODERATION").exists():
Notification(user=u, text=_("New files to be moderated"),
url=reverse("core:file_moderation"), type="FILE_MODERATION").save()
2016-08-10 03:48:06 +00:00
2016-08-10 14:23:12 +00:00
class FileListView(ListView):
2016-08-10 03:48:06 +00:00
template_name = 'core/file_list.jinja'
context_object_name = "file_list"
def get_queryset(self):
return SithFile.objects.filter(parent=None)
def get_context_data(self, **kwargs):
kwargs = super(FileListView, self).get_context_data(**kwargs)
kwargs['popup'] = ""
if self.kwargs['popup']:
kwargs['popup'] = 'popup'
return kwargs
class FileEditView(CanEditMixin, UpdateView):
model = SithFile
pk_url_kwarg = "file_id"
template_name = 'core/file_edit.jinja'
context_object_name = "file"
def get_form_class(self):
2016-11-09 08:13:57 +00:00
fields = ['name', 'is_moderated']
2016-08-10 03:48:06 +00:00
if self.object.is_file:
fields = ['file'] + fields
return modelform_factory(SithFile, fields=fields)
def get_success_url(self):
if self.kwargs['popup']:
return reverse('core:file_detail', kwargs={'file_id': self.object.id, 'popup': "popup"})
return reverse('core:file_detail', kwargs={'file_id': self.object.id, 'popup': ""})
def get_context_data(self, **kwargs):
kwargs = super(FileEditView, self).get_context_data(**kwargs)
kwargs['popup'] = ""
if self.kwargs['popup']:
kwargs['popup'] = 'popup'
return kwargs
class FileEditPropView(CanEditPropMixin, UpdateView):
model = SithFile
pk_url_kwarg = "file_id"
template_name = 'core/file_edit.jinja'
context_object_name = "file"
fields = ['parent', 'owner', 'edit_groups', 'view_groups']
def get_form(self, form_class=None):
form = super(FileEditPropView, self).get_form(form_class)
form.fields['parent'].queryset = SithFile.objects.filter(is_folder=True)
return form
def get_success_url(self):
return reverse('core:file_detail', kwargs={'file_id': self.object.id, 'popup': self.kwargs['popup'] or ""})
def get_context_data(self, **kwargs):
kwargs = super(FileEditPropView, self).get_context_data(**kwargs)
kwargs['popup'] = ""
if self.kwargs['popup']:
kwargs['popup'] = 'popup'
return kwargs
2016-08-10 12:48:18 +00:00
class FileView(CanViewMixin, DetailView, FormMixin):
2016-08-10 03:48:06 +00:00
"""This class handle the upload of new files into a folder"""
model = SithFile
pk_url_kwarg = "file_id"
template_name = 'core/file_detail.jinja'
context_object_name = "file"
form_class = AddFilesForm
2016-08-10 03:48:06 +00:00
def get(self, request, *args, **kwargs):
self.form = self.get_form()
return super(FileView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
self.form = self.get_form()
files = request.FILES.getlist('file_field')
2016-08-10 12:48:18 +00:00
if request.user.is_authenticated() and request.user.can_edit(self.object) and self.form.is_valid():
2016-08-10 03:48:06 +00:00
self.form.process(parent=self.object, owner=request.user, files=files)
if self.form.is_valid():
return super(FileView, self).form_valid(self.form)
return self.form_invalid(self.form)
def get_success_url(self):
return reverse('core:file_detail', kwargs={'file_id': self.object.id, 'popup': self.kwargs['popup'] or ""})
def get_context_data(self, **kwargs):
kwargs = super(FileView, self).get_context_data(**kwargs)
kwargs['popup'] = ""
kwargs['form'] = self.form
if self.kwargs['popup']:
kwargs['popup'] = 'popup'
return kwargs
class FileDeleteView(CanEditPropMixin, DeleteView):
model = SithFile
pk_url_kwarg = "file_id"
template_name = 'core/file_delete_confirm.jinja'
context_object_name = "file"
def get_success_url(self):
self.object.file.delete() # Doing it here or overloading delete() is the same, so let's do it here
2016-11-09 08:13:57 +00:00
if 'next' in self.request.GET.keys():
return self.request.GET['next']
2016-08-10 03:48:06 +00:00
if self.object.parent is None:
return reverse('core:file_list', kwargs={'popup': self.kwargs['popup'] or ""})
return reverse('core:file_detail', kwargs={'file_id': self.object.parent.id, 'popup': self.kwargs['popup'] or ""})
def get_context_data(self, **kwargs):
kwargs = super(FileDeleteView, self).get_context_data(**kwargs)
kwargs['popup'] = ""
if self.kwargs['popup']:
kwargs['popup'] = 'popup'
return kwargs
2016-11-09 08:13:57 +00:00
class FileModerationView(TemplateView):
template_name = "core/file_moderation.jinja"
def get_context_data(self, **kwargs):
kwargs = super(FileModerationView, self).get_context_data(**kwargs)
2016-12-09 14:48:09 +00:00
kwargs['files'] = SithFile.objects.filter(is_moderated=False)[:100]
2016-11-09 08:13:57 +00:00
return kwargs
class FileModerateView(CanEditPropMixin, SingleObjectMixin):
model = SithFile
pk_url_kwarg = "file_id"
def get(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.is_moderated = True
self.object.save()
if 'next' in self.request.GET.keys():
return redirect(self.request.GET['next'])
return redirect('core:file_moderation')