views.py 8.97 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
from core.utils import resize_image, exif_auto_rotate
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 37 38
                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
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
                im = Image.open(BytesIO(f.read()))
Skia's avatar
Skia committed
44 45 46 47
                try:
                    im = exif_auto_rotate(im)
                except: pass
                file = resize_image(im, max(im.size), f.content_type.split('/')[-1])
Skia's avatar
Skia committed
48 49
                thumb = resize_image(im, 200, f.content_type.split('/')[-1])
                compressed = resize_image(im, 600, f.content_type.split('/')[-1])
Skia's avatar
Skia committed
50 51
                new_file.file = file
                new_file.file.name = new_file.name
Skia's avatar
Skia committed
52 53 54 55
                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
56 57 58 59
                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)})

60 61 62 63 64 65 66
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
67 68
class SASMainView(FormView):
    form_class = SASForm
Skia's avatar
Skia committed
69
    template_name = "sas/main.jinja"
Skia's avatar
WIP SAS  
Skia committed
70
    success_url = reverse_lazy('sas:main')
Skia's avatar
Skia committed
71 72 73 74 75

    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
76 77
        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
78
            if self.form.is_valid():
Skia's avatar
Skia committed
79 80 81 82 83
                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
84
        return self.form_invalid(self.form)
Skia's avatar
Skia committed
85 86 87 88 89 90

    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

91
class PictureView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
92
    model = Picture
93
    form_class = RelationForm
Skia's avatar
Skia committed
94 95 96
    pk_url_kwarg = "picture_id"
    template_name = "sas/picture.jinja"

97 98 99 100 101 102
    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
103 104 105 106
        if 'rotate_right' in request.GET.keys():
            self.object.rotate(270)
        if 'rotate_left' in request.GET.keys():
            self.object.rotate(90)
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        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
Skia's avatar
Skia committed
135 136 137
        im = Image.open(BytesIO(self.object.file.read()))
        (w, h) = im.size
        kwargs['is_vertical'] = (w / h) < 1
138 139 140 141 142
        return kwargs

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

Skia's avatar
Skia committed
143 144 145
def send_pict(request, picture_id):
    return send_file(request, picture_id, Picture)

Skia's avatar
Skia committed
146 147 148 149 150 151
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
152
class AlbumView(CanViewMixin, DetailView, FormMixin):
Skia's avatar
Skia committed
153
    model = Album
Skia's avatar
WIP SAS  
Skia committed
154
    form_class = SASForm
Skia's avatar
Skia committed
155 156 157 158 159 160 161 162 163 164
    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
165
        parent = SithFile.objects.filter(id=self.object.id).first()
Skia's avatar
Skia committed
166
        files = request.FILES.getlist('images')
Skia's avatar
WIP SAS  
Skia committed
167
        if request.user.is_authenticated() and request.user.is_in_group('ae-membres'):
Skia's avatar
Skia committed
168
            if self.form.is_valid():
Skia's avatar
WIP SAS  
Skia committed
169 170 171 172
                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
173
            self.form.add_error(None, _("You do not have the permission to do that"))
Skia's avatar
Skia committed
174 175
        return self.form_invalid(self.form)

Skia's avatar
WIP SAS  
Skia committed
176
    def get_success_url(self):
177
        return reverse('sas:album', kwargs={'album_id': self.object.id})
Skia's avatar
WIP SAS  
Skia committed
178 179 180 181 182

    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
183

Skia's avatar
Skia committed
184 185 186 187 188
# Admin views

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

Skia's avatar
Skia committed
189 190 191 192 193 194 195 196 197 198
    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
199
                            pict.asked_for_removal = False
Skia's avatar
Skia committed
200 201 202 203 204
                            pict.save()
                    except: pass
            return super(ModerationView, self).get(request, *args, **kwargs)
        raise PermissionDenied

Skia's avatar
Skia committed
205 206
    def get_context_data(self, **kwargs):
        kwargs = super(ModerationView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
207
        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
208 209 210
        return kwargs