views.py 8.27 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
8
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.conf import settings
from django import forms
Skia's avatar
Skia committed
9
from django.core.exceptions import PermissionDenied
Skia's avatar
Skia committed
10

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

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

Skia's avatar
Skia committed
16
17
18
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
19
from core.models import SithFile, User
Skia's avatar
Skia committed
20

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

Skia's avatar
Skia committed
23
24
25
26
27
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
28
    def process(self, parent, owner, files, automodere=False):
Skia's avatar
Skia committed
29
30
        try:
            if self.cleaned_data['album_name'] != "":
Skia's avatar
Skia committed
31
                album = Album(parent=parent, name=self.cleaned_data['album_name'], owner=owner, is_moderated=automodere)
Skia's avatar
Skia committed
32
33
34
35
36
37
                album.clean()
                album.save()
        except Exception as e:
            self.add_error(None, _("Error creating album %(album)s: %(msg)s") %
                    {'album': self.cleaned_data['album_name'], 'msg': str(e.message)})
        for f in files:
Skia's avatar
WIP SAS    
Skia committed
38
            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
39
                    is_folder=False, is_moderated=automodere)
Skia's avatar
Skia committed
40
41
            try:
                new_file.clean()
Skia's avatar
Skia committed
42
                new_file.generate_thumbnails()
Skia's avatar
Skia committed
43
44
45
46
                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)})

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

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

    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
63
64
        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
65
            if self.form.is_valid():
Skia's avatar
Skia committed
66
67
68
69
70
                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
71
        return self.form_invalid(self.form)
Skia's avatar
Skia committed
72
73
74
75
76
77

    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

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

84
85
86
87
88
89
    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
90
91
92
93
        if 'rotate_right' in request.GET.keys():
            self.object.rotate(270)
        if 'rotate_left' in request.GET.keys():
            self.object.rotate(90)
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
123
124
125
126
        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
127
128
129
def send_pict(request, picture_id):
    return send_file(request, picture_id, Picture)

Skia's avatar
Skia committed
130
131
132
133
134
135
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
136
class AlbumView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
137
    model = Album
Skia's avatar
WIP SAS    
Skia committed
138
    form_class = SASForm
Skia's avatar
Skia committed
139
140
141
142
143
144
145
146
147
148
    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
149
        parent = SithFile.objects.filter(id=self.object.id).first()
Skia's avatar
Skia committed
150
        files = request.FILES.getlist('images')
Skia's avatar
WIP SAS    
Skia committed
151
        if request.user.is_authenticated() and request.user.is_in_group('ae-membres'):
Skia's avatar
Skia committed
152
            if self.form.is_valid():
Skia's avatar
Skia committed
153
154
                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
155
156
157
                if self.form.is_valid():
                    return super(AlbumView, self).form_valid(self.form)
        else:
Skia's avatar
Skia committed
158
            self.form.add_error(None, _("You do not have the permission to do that"))
Skia's avatar
Skia committed
159
160
        return self.form_invalid(self.form)

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

    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
168

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

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

Skia's avatar
Skia committed
174
175
176
177
178
179
180
181
182
183
    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
184
                            pict.asked_for_removal = False
Skia's avatar
Skia committed
185
186
187
188
189
                            pict.save()
                    except: pass
            return super(ModerationView, self).get(request, *args, **kwargs)
        raise PermissionDenied

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