views.py 8.46 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
13
14
15

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

18
from sas.models import Picture, Album, PeoplePictureRelation
Skia's avatar
Skia committed
19

Skia's avatar
Skia committed
20
21
22
23
24
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
25
    def process(self, parent, owner, files, automodere=False):
Skia's avatar
Skia committed
26
27
28
        from core.utils import resize_image
        from io import BytesIO
        from PIL import Image
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
43
44
45
46
47
48
                im = Image.open(BytesIO(f.read()))
                thumb = resize_image(im, 200, f.content_type.split('/')[-1])
                compressed = resize_image(im, 600, f.content_type.split('/')[-1])
                new_file.thumbnail = thumb
                new_file.thumbnail.name = new_file.name
                new_file.compressed = compressed
                new_file.compressed.name = new_file.name
Skia's avatar
Skia committed
49
                new_file.save()
Skia's avatar
Skia committed
50
                print(new_file.compressed)
Skia's avatar
Skia committed
51
52
53
            except Exception as e:
                self.add_error(None, _("Error uploading file %(file_name)s: %(msg)s") % {'file_name': f, 'msg': repr(e)})

54
55
56
57
58
59
60
class RelationForm(forms.ModelForm):
    class Meta:
        model = PeoplePictureRelation
        fields = ['picture', 'user']
        widgets = {'picture': forms.HiddenInput}
    user = make_ajax_field(PeoplePictureRelation, 'user', 'users', help_text="")

Skia's avatar
Skia committed
61
62
class SASMainView(FormView):
    form_class = SASForm
Skia's avatar
Skia committed
63
    template_name = "sas/main.jinja"
Skia's avatar
WIP SAS  
Skia committed
64
    success_url = reverse_lazy('sas:main')
Skia's avatar
Skia committed
65
66
67
68
69

    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
70
71
        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
72
            if self.form.is_valid():
Skia's avatar
Skia committed
73
74
75
76
77
                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
78
        return self.form_invalid(self.form)
Skia's avatar
Skia committed
79
80
81
82
83
84

    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

85
class PictureView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
86
    model = Picture
87
    form_class = RelationForm
Skia's avatar
Skia committed
88
89
90
    pk_url_kwarg = "picture_id"
    template_name = "sas/picture.jinja"

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
123
124
125
126
127
128
129
    def get_initial(self):
        return {'picture': self.object}

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.form = self.get_form()
        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
130
131
132
def send_pict(request, picture_id):
    return send_file(request, picture_id, Picture)

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

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

    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
170

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

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

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

Skia's avatar
Skia committed
192
193
    def get_context_data(self, **kwargs):
        kwargs = super(ModerationView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
194
        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
195
196
197
        return kwargs