files.py 10.9 KB
Newer Older
Skia's avatar
Skia committed
1
2
# This file contains all the views that concern the page model
from django.shortcuts import render, redirect, get_object_or_404
Skia's avatar
Skia committed
3
from django.views.generic import ListView, DetailView, TemplateView
Skia's avatar
Skia committed
4
from django.views.generic.edit import UpdateView, CreateView, FormMixin, DeleteView
Skia's avatar
Skia committed
5
from django.views.generic.detail import SingleObjectMixin
Skia's avatar
Skia committed
6
7
8
9
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
10
from django.utils.translation import ugettext_lazy as _
Skia's avatar
Skia committed
11
12
13
14
15
16
17
18
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

Skia's avatar
Skia committed
19
20
from ajax_select import make_ajax_form, make_ajax_field

Skia's avatar
Skia committed
21
from core.models import SithFile, RealGroup, Notification
Skia's avatar
Skia committed
22
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin, can_view, not_found
Skia's avatar
Skia committed
23
from counter.models import Counter
Skia's avatar
Skia committed
24

Skia's avatar
Skia committed
25
def send_file(request, file_id, file_class=SithFile, file_attr="file"):
Skia's avatar
Skia committed
26
27
28
29
30
    """
    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.
    """
Skia's avatar
Skia committed
31
    f = file_class.objects.filter(id=file_id).first()
Skia's avatar
Skia committed
32
    if f is None or not f.file:
Skia's avatar
Skia committed
33
        return not_found(request)
34
35
36
37
38
    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())
            ):
Skia's avatar
Skia committed
39
        raise PermissionDenied
Skia's avatar
Skia committed
40
    name = f.__getattribute__(file_attr).name
Sli's avatar
Sli committed
41
42
    filepath = os.path.join(settings.MEDIA_ROOT, name)
    with open(filepath.encode('utf-8'), 'rb') as filename:
Skia's avatar
Skia committed
43
44
        wrapper = FileWrapper(filename)
        response = HttpResponse(wrapper, content_type=f.mime_type)
Sli's avatar
Sli committed
45
        response['Content-Length'] = os.path.getsize(filepath.encode('utf-8'))
Skia's avatar
Skia committed
46
        response['Content-Disposition'] = ('inline; filename="%s"' % f.name).encode('utf-8')
Skia's avatar
Skia committed
47
48
        return response

49
class AddFilesForm(forms.Form):
Skia's avatar
Skia committed
50
51
52
53
54
    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):
Skia's avatar
Skia committed
55
        notif = False
Skia's avatar
Skia committed
56
57
58
59
60
        try:
            if self.cleaned_data['folder_name'] != "":
                folder = SithFile(parent=parent, name=self.cleaned_data['folder_name'], owner=owner)
                folder.clean()
                folder.save()
Skia's avatar
Skia committed
61
                notif = True
Skia's avatar
Skia committed
62
63
        except Exception as e:
            self.add_error(None, _("Error creating folder %(folder_name)s: %(msg)s") %
Skia's avatar
Skia committed
64
                    {'folder_name': self.cleaned_data['folder_name'], 'msg': repr(e)})
Skia's avatar
Skia committed
65
66
67
68
69
70
        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()
Skia's avatar
Skia committed
71
                notif = True
Skia's avatar
Skia committed
72
            except Exception as e:
Skia's avatar
Skia committed
73
                self.add_error(None, _("Error uploading file %(file_name)s: %(msg)s") % {'file_name': f, 'msg': repr(e)})
Skia's avatar
Skia committed
74
        if notif:
Skia's avatar
Skia committed
75
            for u in RealGroup.objects.filter(id=settings.SITH_GROUP_COM_ADMIN_ID).first().users.all():
Skia's avatar
Skia committed
76
                if not u.notifications.filter(type="FILE_MODERATION", viewed=False).exists():
Skia's avatar
Skia committed
77
                    Notification(user=u, url=reverse("core:file_moderation"), type="FILE_MODERATION").save()
Skia's avatar
Skia committed
78

Skia's avatar
Skia committed
79
class FileListView(ListView):
Skia's avatar
Skia committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
    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):
Skia's avatar
Skia committed
100
        fields = ['name', 'is_moderated']
Skia's avatar
Skia committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        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

Skia's avatar
Skia committed
117
118
119
120
121
class FileEditPropForm(forms.ModelForm):
    class Meta:
        model = SithFile
        fields = ['parent', 'owner', 'edit_groups', 'view_groups']
    parent = make_ajax_field(SithFile, 'parent', 'files', help_text="")
122
123
    edit_groups = make_ajax_field(SithFile, 'edit_groups', 'groups', help_text="", label=_("edit group"))
    view_groups = make_ajax_field(SithFile, 'view_groups', 'groups', help_text="", label=_("view group"))
Skia's avatar
Skia committed
124
    recursive = forms.BooleanField(label=_("Apply rights recursively"), required=False)
Skia's avatar
Skia committed
125

Skia's avatar
Skia committed
126
127
128
129
130
class FileEditPropView(CanEditPropMixin, UpdateView):
    model = SithFile
    pk_url_kwarg = "file_id"
    template_name = 'core/file_edit.jinja'
    context_object_name = "file"
Skia's avatar
Skia committed
131
    form_class = FileEditPropForm
Skia's avatar
Skia committed
132
133
134
135
136
137

    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

Skia's avatar
Skia committed
138
139
140
141
142
143
    def form_valid(self, form):
        ret = super(FileEditPropView, self).form_valid(form)
        if form.cleaned_data['recursive']:
            self.object.apply_rights_recursively()
        return ret

Skia's avatar
Skia committed
144
145
146
147
148
149
150
151
152
153
    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
154
class FileView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
155
156
157
158
159
    """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"
160
    form_class = AddFilesForm
Skia's avatar
Skia committed
161

Skia's avatar
Skia committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    def handle_clipboard(request, object):
        if 'delete' in request.POST.keys():
            for f_id in request.POST.getlist('file_list'):
                sf = SithFile.objects.filter(id=f_id).first()
                if sf:
                    sf.delete()
        if 'clear' in request.POST.keys():
            request.session['clipboard'] = []
        if 'cut' in request.POST.keys():
            for f_id in request.POST.getlist('file_list'):
                f_id = int(f_id)
                if f_id in [c.id for c in object.children.all()] and f_id not in request.session['clipboard']:
                    print(f_id)
                    request.session['clipboard'].append(f_id)
        if 'paste' in request.POST.keys():
            for f_id in request.session['clipboard']:
                sf = SithFile.objects.filter(id=f_id).first()
                if sf:
                    sf.move_to(object)
            request.session['clipboard'] = []
        request.session.modified = True

Skia's avatar
Skia committed
184
185
    def get(self, request, *args, **kwargs):
        self.form = self.get_form()
186
187
        if 'clipboard' not in request.session.keys():
            request.session['clipboard'] = []
Skia's avatar
Skia committed
188
189
190
191
        return super(FileView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
192
193
        if 'clipboard' not in request.session.keys():
            request.session['clipboard'] = []
Skia's avatar
Skia committed
194
        if request.user.can_edit(self.object):
Skia's avatar
Skia committed
195
            FileView.handle_clipboard(request, self.object)
Skia's avatar
Skia committed
196
        self.form = self.get_form() # The form handle only the file upload
Skia's avatar
Skia committed
197
        files = request.FILES.getlist('file_field')
Skia's avatar
Skia committed
198
        if request.user.is_authenticated() and request.user.can_edit(self.object) and self.form.is_valid():
Skia's avatar
Skia committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
            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'
213
        kwargs['clipboard'] = SithFile.objects.filter(id__in=self.request.session['clipboard'])
Skia's avatar
Skia committed
214
215
216
217
218
219
220
221
222
223
        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
Skia's avatar
Skia committed
224
225
        if 'next' in self.request.GET.keys():
            return self.request.GET['next']
Skia's avatar
Skia committed
226
227
228
229
230
231
232
233
234
235
236
        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

Skia's avatar
Skia committed
237
238
239
240
241
class FileModerationView(TemplateView):
    template_name = "core/file_moderation.jinja"

    def get_context_data(self, **kwargs):
        kwargs = super(FileModerationView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
242
        kwargs['files'] = SithFile.objects.filter(is_moderated=False)[:100]
Skia's avatar
Skia committed
243
244
245
246
247
248
249
250
251
        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
Skia's avatar
Skia committed
252
        self.object.moderator = request.user
Skia's avatar
Skia committed
253
254
255
256
257
        self.object.save()
        if 'next' in self.request.GET.keys():
            return redirect(self.request.GET['next'])
        return redirect('core:file_moderation')