files.py 6.99 KB
Newer Older
Skia's avatar
Skia committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
# This file contains all the views that concern the page model
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, CreateView, FormMixin, DeleteView
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

from core.models import SithFile
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin, can_view, not_found

def send_file(request, file_id):
    """
    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.
    """
    f = SithFile.objects.filter(id=file_id).first()
    if f is None or f.is_folder:
        return not_found(request)
    if not can_view(f, request.user):
        raise PermissionDenied
    name = f.file.name
    with open(settings.MEDIA_ROOT + name, 'rb') as filename:
        wrapper = FileWrapper(filename)
        response = HttpResponse(wrapper, content_type=f.mime_type)
        response['Content-Length'] = os.path.getsize(settings.MEDIA_ROOT + name)
        response['Content-Disposition'] = 'inline; filename="%s"' % f.name
        return response

40
class AddFilesForm(forms.Form):
Skia's avatar
Skia committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    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):
        try:
            if self.cleaned_data['folder_name'] != "":
                folder = SithFile(parent=parent, name=self.cleaned_data['folder_name'], owner=owner)
                folder.clean()
                folder.save()
        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()
            except Exception as e:
Skia's avatar
Skia committed
61
                self.add_error(None, _("Error uploading file %(file_name)s: %(msg)s") % {'file_name': f, 'msg': repr(e)})
Skia's avatar
Skia committed
62

Skia's avatar
Skia committed
63
class FileListView(ListView):
Skia's avatar
Skia committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    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):
        fields = ['name']
        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

Skia's avatar
Skia committed
123
class FileView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
124 125 126 127 128
    """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"
129
    form_class = AddFilesForm
Skia's avatar
Skia committed
130 131 132 133 134 135 136 137 138

    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')
Skia's avatar
Skia committed
139
        if request.user.is_authenticated() and request.user.can_edit(self.object) and self.form.is_valid():
Skia's avatar
Skia committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            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
        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