views.py 8.94 KB
Newer Older
1
2
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse_lazy, reverse
Skia's avatar
Skia committed
3
from django.views.generic import ListView, DetailView, RedirectView, TemplateView
Skia's avatar
Skia committed
4
from django.views.generic.edit import UpdateView, CreateView, DeleteView, ProcessFormView, FormMixin, FormView
Skia's avatar
Skia committed
5
6
7
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.conf import settings
Skia's avatar
Skia committed
8
from django.forms.models import modelform_factory
Skia's avatar
Skia committed
9
from django import forms
Skia's avatar
Skia committed
10
from django.core.exceptions import PermissionDenied
Skia's avatar
Skia committed
11

12
from ajax_select import make_ajax_form, make_ajax_field
Skia's avatar
Skia committed
13

Skia's avatar
Skia committed
14
15
16
from io import BytesIO
from PIL import Image

Skia's avatar
Skia committed
17
18
19
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin, TabedViewMixin
from core.views.forms import SelectUser, LoginForm, SelectDate, SelectDateTime
from core.views.files import send_file
Skia's avatar
Skia committed
20
from core.models import SithFile, User
Skia's avatar
Skia committed
21

22
from sas.models import Picture, Album, PeoplePictureRelation
Skia's avatar
Skia committed
23

Skia's avatar
Skia committed
24
25
26
27
28
class SASForm(forms.Form):
    album_name = forms.CharField(label=_("Add a new album"), max_length=30, required=False)
    images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), label=_("Upload images"),
            required=False)

Skia's avatar
Skia committed
29
    def process(self, parent, owner, files, automodere=False):
Skia's avatar
Skia committed
30
31
        try:
            if self.cleaned_data['album_name'] != "":
Skia's avatar
Skia committed
32
                album = Album(parent=parent, name=self.cleaned_data['album_name'], owner=owner, is_moderated=automodere)
Skia's avatar
Skia committed
33
34
35
36
                album.clean()
                album.save()
        except Exception as e:
            self.add_error(None, _("Error creating album %(album)s: %(msg)s") %
37
                    {'album': self.cleaned_data['album_name'], 'msg': repr(e)})
Skia's avatar
Skia committed
38
        for f in files:
Skia's avatar
WIP SAS    
Skia committed
39
            new_file = Picture(parent=parent, name=f.name, file=f, owner=owner, mime_type=f.content_type, size=f._size,
Skia's avatar
Skia committed
40
                    is_folder=False, is_moderated=automodere)
Skia's avatar
Skia committed
41
42
            try:
                new_file.clean()
Skia's avatar
Skia committed
43
                new_file.generate_thumbnails()
Skia's avatar
Skia committed
44
45
46
47
                new_file.save()
            except Exception as e:
                self.add_error(None, _("Error uploading file %(file_name)s: %(msg)s") % {'file_name': f, 'msg': repr(e)})

48
49
50
51
52
class RelationForm(forms.ModelForm):
    class Meta:
        model = PeoplePictureRelation
        fields = ['picture', 'user']
        widgets = {'picture': forms.HiddenInput}
Skia's avatar
Skia committed
53
    user = make_ajax_field(PeoplePictureRelation, 'user', 'users', label=_("Add user"))
54

Skia's avatar
Skia committed
55
56
class SASMainView(FormView):
    form_class = SASForm
Skia's avatar
Skia committed
57
    template_name = "sas/main.jinja"
Skia's avatar
WIP SAS    
Skia committed
58
    success_url = reverse_lazy('sas:main')
Skia's avatar
Skia committed
59
60
61
62
63

    def post(self, request, *args, **kwargs):
        self.form = self.get_form()
        parent = SithFile.objects.filter(id=settings.SITH_SAS_ROOT_DIR_ID).first()
        files = request.FILES.getlist('images')
Skia's avatar
Skia committed
64
65
        root = User.objects.filter(username="root").first()
        if request.user.is_authenticated() and request.user.is_in_group(settings.SITH_SAS_ADMIN_GROUP_ID):
Skia's avatar
Skia committed
66
            if self.form.is_valid():
Skia's avatar
Skia committed
67
68
69
70
71
                self.form.process(parent=parent, owner=root, files=files, automodere=True)
                if self.form.is_valid():
                    return super(SASMainView, self).form_valid(self.form)
        else:
            self.form.add_error(None, _("You do not have the permission to do that"))
Skia's avatar
Skia committed
72
        return self.form_invalid(self.form)
Skia's avatar
Skia committed
73
74
75
76
77
78

    def get_context_data(self, **kwargs):
        kwargs = super(SASMainView, self).get_context_data(**kwargs)
        kwargs['root_file'] = SithFile.objects.filter(id=settings.SITH_SAS_ROOT_DIR_ID).first()
        return kwargs

79
class PictureView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
80
    model = Picture
81
    form_class = RelationForm
Skia's avatar
Skia committed
82
83
84
    pk_url_kwarg = "picture_id"
    template_name = "sas/picture.jinja"

85
86
87
88
89
90
    def get_initial(self):
        return {'picture': self.object}

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.form = self.get_form()
Skia's avatar
Skia committed
91
92
93
94
        if 'rotate_right' in request.GET.keys():
            self.object.rotate(270)
        if 'rotate_left' in request.GET.keys():
            self.object.rotate(90)
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
123
124
125
126
127
        if 'remove_user' in request.GET.keys():
            try:
                user = User.objects.filter(id=int(request.GET['remove_user'])).first()
                if user.id == request.user.id or request.user.is_in_group(settings.SITH_SAS_ADMIN_GROUP_ID):
                    r = PeoplePictureRelation.objects.filter(user=user, picture=self.object).delete()
            except: pass
        if 'ask_removal' in request.GET.keys():
            self.object.is_moderated = False
            self.object.asked_for_removal = True
            self.object.save()
            return redirect("sas:album", album_id=self.object.parent.id)
        return super(PictureView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.form = self.get_form()
        if request.user.is_authenticated() and request.user.is_in_group('ae-membres'):
            if self.form.is_valid():
                PeoplePictureRelation(user=self.form.cleaned_data['user'],
                        picture=self.form.cleaned_data['picture']).save()
                return super(PictureView, self).form_valid(self.form)
        else:
            self.form.add_error(None, _("You do not have the permission to do that"))
        return self.form_invalid(self.form)

    def get_context_data(self, **kwargs):
        kwargs = super(PictureView, self).get_context_data(**kwargs)
        kwargs['form'] = self.form
        return kwargs

    def get_success_url(self):
        return reverse('sas:picture', kwargs={'picture_id': self.object.id})

Skia's avatar
Skia committed
128
129
130
def send_pict(request, picture_id):
    return send_file(request, picture_id, Picture)

Skia's avatar
Skia committed
131
132
133
134
135
136
def send_compressed(request, picture_id):
    return send_file(request, picture_id, Picture, "compressed")

def send_thumb(request, picture_id):
    return send_file(request, picture_id, Picture, "thumbnail")

Skia's avatar
WIP SAS    
Skia committed
137
class AlbumView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
138
    model = Album
Skia's avatar
WIP SAS    
Skia committed
139
    form_class = SASForm
Skia's avatar
Skia committed
140
141
142
143
144
145
146
147
148
149
    pk_url_kwarg = "album_id"
    template_name = "sas/album.jinja"

    def get(self, request, *args, **kwargs):
        self.form = self.get_form()
        return super(AlbumView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.form = self.get_form()
Skia's avatar
WIP SAS    
Skia committed
150
        parent = SithFile.objects.filter(id=self.object.id).first()
Skia's avatar
Skia committed
151
        files = request.FILES.getlist('images')
Skia's avatar
WIP SAS    
Skia committed
152
        if request.user.is_authenticated() and request.user.is_in_group('ae-membres'):
Skia's avatar
Skia committed
153
            if self.form.is_valid():
Skia's avatar
Skia committed
154
155
                self.form.process(parent=parent, owner=request.user, files=files,
                        automodere=request.user.is_in_group(settings.SITH_SAS_ADMIN_GROUP_ID))
Skia's avatar
WIP SAS    
Skia committed
156
157
158
                if self.form.is_valid():
                    return super(AlbumView, self).form_valid(self.form)
        else:
Skia's avatar
Skia committed
159
            self.form.add_error(None, _("You do not have the permission to do that"))
Skia's avatar
Skia committed
160
161
        return self.form_invalid(self.form)

Skia's avatar
WIP SAS    
Skia committed
162
    def get_success_url(self):
163
        return reverse('sas:album', kwargs={'album_id': self.object.id})
Skia's avatar
WIP SAS    
Skia committed
164
165
166
167
168

    def get_context_data(self, **kwargs):
        kwargs = super(AlbumView, self).get_context_data(**kwargs)
        kwargs['form'] = self.form
        return kwargs
Skia's avatar
Skia committed
169

Skia's avatar
Skia committed
170
171
172
173
174
# Admin views

class ModerationView(TemplateView):
    template_name = "sas/moderation.jinja"

Skia's avatar
Skia committed
175
176
177
178
179
180
181
182
183
184
    def get(self, request, *args, **kwargs):
        if request.user.is_in_group(settings.SITH_SAS_ADMIN_GROUP_ID):
            for k,v in request.GET.items():
                if k[:7] == "action_":
                    try:
                        pict = Picture.objects.filter(id=int(k[7:])).first()
                        if v == "delete":
                            pict.delete()
                        elif v == "moderate":
                            pict.is_moderated = True
185
                            pict.asked_for_removal = False
Skia's avatar
Skia committed
186
187
188
189
190
                            pict.save()
                    except: pass
            return super(ModerationView, self).get(request, *args, **kwargs)
        raise PermissionDenied

Skia's avatar
Skia committed
191
192
    def get_context_data(self, **kwargs):
        kwargs = super(ModerationView, self).get_context_data(**kwargs)
193
        kwargs['pictures'] = Picture.objects.filter(is_moderated=False, is_in_sas=True).order_by('id')
Skia's avatar
Skia committed
194
195
        return kwargs

Skia's avatar
Skia committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
class PictureEditForm(forms.ModelForm):
    class Meta:
        model = Picture
        fields=['name', 'parent']
    parent = make_ajax_field(Picture, 'parent', 'files', help_text="")

class AlbumEditForm(forms.ModelForm):
    class Meta:
        model = Album
        fields=['name', 'parent']
    parent = make_ajax_field(Album, 'parent', 'files', help_text="")

class PictureEditView(UpdateView):
    model=Picture
    form_class=PictureEditForm
    template_name='core/edit.jinja'
    pk_url_kwarg = "picture_id"

class AlbumEditView(UpdateView):
    model=Album
    form_class=AlbumEditForm
    template_name='core/edit.jinja'
    pk_url_kwarg = "album_id"
Skia's avatar
Skia committed
219