Format sas

This commit is contained in:
Pierre Brunet 2017-06-12 10:02:38 +02:00
parent 13ec91e7e5
commit e2311dcb71
4 changed files with 52 additions and 45 deletions

View File

@ -30,5 +30,3 @@ from sas.models import *
admin.site.register(Album) admin.site.register(Album)
# admin.site.register(Picture) # admin.site.register(Picture)
admin.site.register(PeoplePictureRelation) admin.site.register(PeoplePictureRelation)

View File

@ -23,11 +23,9 @@
# #
from django.db import models from django.db import models
from django.core.urlresolvers import reverse_lazy, reverse
from django.conf import settings
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.core.files.base import ContentFile
from PIL import Image from PIL import Image
from io import BytesIO from io import BytesIO
@ -36,6 +34,7 @@ import os
from core.models import SithFile, User from core.models import SithFile, User
from core.utils import resize_image, exif_auto_rotate from core.utils import resize_image, exif_auto_rotate
class Picture(SithFile): class Picture(SithFile):
class Meta: class Meta:
proxy = True proxy = True
@ -50,12 +49,12 @@ class Picture(SithFile):
def can_be_edited_by(self, user): def can_be_edited_by(self, user):
# file = SithFile.objects.filter(id=self.id).first() # file = SithFile.objects.filter(id=self.id).first()
return user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID)# or user.can_edit(file) return user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID) # or user.can_edit(file)
def can_be_viewed_by(self, user): def can_be_viewed_by(self, user):
# file = SithFile.objects.filter(id=self.id).first() # file = SithFile.objects.filter(id=self.id).first()
return self.can_be_edited_by(user) or (self.is_in_sas and self.is_moderated and return self.can_be_edited_by(user) or (self.is_in_sas and self.is_moderated and
user.was_subscribed)# or user.can_view(file) user.was_subscribed) # or user.can_view(file)
def get_download_url(self): def get_download_url(self):
return reverse('sas:download', kwargs={'picture_id': self.id}) return reverse('sas:download', kwargs={'picture_id': self.id})
@ -73,7 +72,8 @@ class Picture(SithFile):
im = Image.open(BytesIO(self.file.read())) im = Image.open(BytesIO(self.file.read()))
try: try:
im = exif_auto_rotate(im) im = exif_auto_rotate(im)
except: pass except:
pass
file = resize_image(im, max(im.size), self.mime_type.split('/')[-1]) file = resize_image(im, max(im.size), self.mime_type.split('/')[-1])
thumb = resize_image(im, 200, self.mime_type.split('/')[-1]) thumb = resize_image(im, 200, self.mime_type.split('/')[-1])
compressed = resize_image(im, 1200, self.mime_type.split('/')[-1]) compressed = resize_image(im, 1200, self.mime_type.split('/')[-1])
@ -102,17 +102,18 @@ class Picture(SithFile):
def get_next(self): def get_next(self):
if self.is_moderated: if self.is_moderated:
return self.parent.children.filter(is_moderated=True, asked_for_removal=False, is_folder=False, return self.parent.children.filter(is_moderated=True, asked_for_removal=False, is_folder=False,
id__gt=self.id).order_by('id').first() id__gt=self.id).order_by('id').first()
else: else:
return Picture.objects.filter(id__gt=self.id, is_moderated=False, is_in_sas=True).order_by('id').first() return Picture.objects.filter(id__gt=self.id, is_moderated=False, is_in_sas=True).order_by('id').first()
def get_previous(self): def get_previous(self):
if self.is_moderated: if self.is_moderated:
return self.parent.children.filter(is_moderated=True, asked_for_removal=False, is_folder=False, return self.parent.children.filter(is_moderated=True, asked_for_removal=False, is_folder=False,
id__lt=self.id).order_by('id').last() id__lt=self.id).order_by('id').last()
else: else:
return Picture.objects.filter(id__lt=self.id, is_moderated=False, is_in_sas=True).order_by('-id').first() return Picture.objects.filter(id__lt=self.id, is_moderated=False, is_in_sas=True).order_by('-id').first()
class Album(SithFile): class Album(SithFile):
class Meta: class Meta:
proxy = True proxy = True
@ -127,12 +128,12 @@ class Album(SithFile):
def can_be_edited_by(self, user): def can_be_edited_by(self, user):
# file = SithFile.objects.filter(id=self.id).first() # file = SithFile.objects.filter(id=self.id).first()
return user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID)# or user.can_edit(file) return user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID) # or user.can_edit(file)
def can_be_viewed_by(self, user): def can_be_viewed_by(self, user):
# file = SithFile.objects.filter(id=self.id).first() # file = SithFile.objects.filter(id=self.id).first()
return self.can_be_edited_by(user) or (self.is_in_sas and self.is_moderated and return self.can_be_edited_by(user) or (self.is_in_sas and self.is_moderated and
user.was_subscribed)# or user.can_view(file) user.was_subscribed) # or user.can_view(file)
def get_absolute_url(self): def get_absolute_url(self):
return reverse('sas:album', kwargs={'album_id': self.id}) return reverse('sas:album', kwargs={'album_id': self.id})
@ -148,6 +149,7 @@ class Album(SithFile):
self.file.name = self.name + '/thumb.jpg' self.file.name = self.name + '/thumb.jpg'
self.save() self.save()
class PeoplePictureRelation(models.Model): class PeoplePictureRelation(models.Model):
""" """
The PeoplePictureRelation class makes the connection between User and Picture The PeoplePictureRelation class makes the connection between User and Picture

View File

@ -22,7 +22,7 @@
# #
# #
from django.conf.urls import url, include from django.conf.urls import url
from sas.views import * from sas.views import *
@ -40,4 +40,3 @@ urlpatterns = [
# url(r'^album/new$', AlbumCreateView.as_view(), name='album_new'), # url(r'^album/new$', AlbumCreateView.as_view(), name='album_new'),
# url(r'^(?P<club_id>[0-9]+)/$', ClubView.as_view(), name='club_view'), # url(r'^(?P<club_id>[0-9]+)/$', ClubView.as_view(), name='club_view'),
] ]

View File

@ -22,35 +22,30 @@
# #
# #
from django.shortcuts import render, redirect from django.shortcuts import redirect
from django.http import HttpResponseRedirect, HttpResponse from django.http import HttpResponse
from django.core.urlresolvers import reverse_lazy, reverse from django.core.urlresolvers import reverse_lazy, reverse
from django.views.generic import ListView, DetailView, RedirectView, TemplateView from django.views.generic import DetailView, TemplateView
from django.views.generic.edit import UpdateView, CreateView, DeleteView, ProcessFormView, FormMixin, FormView from django.views.generic.edit import UpdateView, FormMixin, FormView
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.conf import settings from django.conf import settings
from django.forms.models import modelform_factory
from django import forms from django import forms
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from ajax_select import make_ajax_form, make_ajax_field from ajax_select import make_ajax_field
from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField from ajax_select.fields import AutoCompleteSelectMultipleField
from io import BytesIO from core.views import CanViewMixin, CanEditMixin
from PIL import Image
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, FileView from core.views.files import send_file, FileView
from core.models import SithFile, User, Notification, RealGroup from core.models import SithFile, User, Notification, RealGroup
from sas.models import Picture, Album, PeoplePictureRelation from sas.models import Picture, Album, PeoplePictureRelation
class SASForm(forms.Form): class SASForm(forms.Form):
album_name = forms.CharField(label=_("Add a new album"), max_length=30, required=False) 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"), images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), label=_("Upload images"),
required=False) required=False)
def process(self, parent, owner, files, automodere=False): def process(self, parent, owner, files, automodere=False):
notif = False notif = False
@ -62,10 +57,10 @@ class SASForm(forms.Form):
notif = not automodere notif = not automodere
except Exception as e: except Exception as e:
self.add_error(None, _("Error creating album %(album)s: %(msg)s") % self.add_error(None, _("Error creating album %(album)s: %(msg)s") %
{'album': self.cleaned_data['album_name'], 'msg': repr(e)}) {'album': self.cleaned_data['album_name'], 'msg': repr(e)})
for f in files: for f in files:
new_file = Picture(parent=parent, name=f.name, file=f, owner=owner, mime_type=f.content_type, size=f._size, new_file = Picture(parent=parent, name=f.name, file=f, owner=owner, mime_type=f.content_type, size=f._size,
is_folder=False, is_moderated=automodere) is_folder=False, is_moderated=automodere)
if automodere: if automodere:
new_file.moderator = owner new_file.moderator = owner
try: try:
@ -80,6 +75,7 @@ class SASForm(forms.Form):
if not u.notifications.filter(type="SAS_MODERATION", viewed=False).exists(): if not u.notifications.filter(type="SAS_MODERATION", viewed=False).exists():
Notification(user=u, url=reverse("sas:moderation"), type="SAS_MODERATION").save() Notification(user=u, url=reverse("sas:moderation"), type="SAS_MODERATION").save()
class RelationForm(forms.ModelForm): class RelationForm(forms.ModelForm):
class Meta: class Meta:
model = PeoplePictureRelation model = PeoplePictureRelation
@ -87,6 +83,7 @@ class RelationForm(forms.ModelForm):
widgets = {'picture': forms.HiddenInput} widgets = {'picture': forms.HiddenInput}
users = AutoCompleteSelectMultipleField('users', show_help_text=False, help_text="", label=_("Add user"), required=False) users = AutoCompleteSelectMultipleField('users', show_help_text=False, help_text="", label=_("Add user"), required=False)
class SASMainView(FormView): class SASMainView(FormView):
form_class = SASForm form_class = SASForm
template_name = "sas/main.jinja" template_name = "sas/main.jinja"
@ -112,6 +109,7 @@ class SASMainView(FormView):
kwargs['latest'] = SithFile.objects.filter(is_in_sas=True, is_folder=True, is_moderated=True).order_by('-id')[:5] kwargs['latest'] = SithFile.objects.filter(is_in_sas=True, is_folder=True, is_moderated=True).order_by('-id')[:5]
return kwargs return kwargs
class PictureView(CanViewMixin, DetailView, FormMixin): class PictureView(CanViewMixin, DetailView, FormMixin):
model = Picture model = Picture
form_class = RelationForm form_class = RelationForm
@ -133,7 +131,8 @@ class PictureView(CanViewMixin, DetailView, FormMixin):
user = User.objects.filter(id=int(request.GET['remove_user'])).first() 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_GROUP_SAS_ADMIN_ID): if user.id == request.user.id or request.user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID):
r = PeoplePictureRelation.objects.filter(user=user, picture=self.object).delete() r = PeoplePictureRelation.objects.filter(user=user, picture=self.object).delete()
except: pass except:
pass
if 'ask_removal' in request.GET.keys(): if 'ask_removal' in request.GET.keys():
self.object.is_moderated = False self.object.is_moderated = False
self.object.asked_for_removal = True self.object.asked_for_removal = True
@ -149,7 +148,7 @@ class PictureView(CanViewMixin, DetailView, FormMixin):
for uid in self.form.cleaned_data['users']: for uid in self.form.cleaned_data['users']:
u = User.objects.filter(id=uid).first() u = User.objects.filter(id=uid).first()
PeoplePictureRelation(user=u, PeoplePictureRelation(user=u,
picture=self.form.cleaned_data['picture']).save() picture=self.form.cleaned_data['picture']).save()
if not u.notifications.filter(type="NEW_PICTURES", viewed=False).exists(): if not u.notifications.filter(type="NEW_PICTURES", viewed=False).exists():
Notification(user=u, url=reverse("core:user_pictures", kwargs={'user_id': u.id}), type="NEW_PICTURES").save() Notification(user=u, url=reverse("core:user_pictures", kwargs={'user_id': u.id}), type="NEW_PICTURES").save()
return super(PictureView, self).form_valid(self.form) return super(PictureView, self).form_valid(self.form)
@ -165,15 +164,19 @@ class PictureView(CanViewMixin, DetailView, FormMixin):
def get_success_url(self): def get_success_url(self):
return reverse('sas:picture', kwargs={'picture_id': self.object.id}) return reverse('sas:picture', kwargs={'picture_id': self.object.id})
def send_pict(request, picture_id): def send_pict(request, picture_id):
return send_file(request, picture_id, Picture) return send_file(request, picture_id, Picture)
def send_compressed(request, picture_id): def send_compressed(request, picture_id):
return send_file(request, picture_id, Picture, "compressed") return send_file(request, picture_id, Picture, "compressed")
def send_thumb(request, picture_id): def send_thumb(request, picture_id):
return send_file(request, picture_id, Picture, "thumbnail") return send_file(request, picture_id, Picture, "thumbnail")
class AlbumUploadView(CanViewMixin, DetailView, FormMixin): class AlbumUploadView(CanViewMixin, DetailView, FormMixin):
model = Album model = Album
form_class = SASForm form_class = SASForm
@ -189,7 +192,7 @@ class AlbumUploadView(CanViewMixin, DetailView, FormMixin):
if request.user.is_authenticated() and request.user.is_subscribed: if request.user.is_authenticated() and request.user.is_subscribed:
if self.form.is_valid(): if self.form.is_valid():
self.form.process(parent=parent, owner=request.user, files=files, self.form.process(parent=parent, owner=request.user, files=files,
automodere=request.user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID)) automodere=request.user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID))
if self.form.is_valid(): if self.form.is_valid():
return HttpResponse(str(self.form.errors), status=200) return HttpResponse(str(self.form.errors), status=200)
return HttpResponse(str(self.form.errors), status=500) return HttpResponse(str(self.form.errors), status=500)
@ -214,14 +217,14 @@ class AlbumView(CanViewMixin, DetailView, FormMixin):
self.form = self.get_form() self.form = self.get_form()
if 'clipboard' not in request.session.keys(): if 'clipboard' not in request.session.keys():
request.session['clipboard'] = [] request.session['clipboard'] = []
if request.user.can_edit(self.object): # Handle the copy-paste functions if request.user.can_edit(self.object): # Handle the copy-paste functions
FileView.handle_clipboard(request, self.object) FileView.handle_clipboard(request, self.object)
parent = SithFile.objects.filter(id=self.object.id).first() parent = SithFile.objects.filter(id=self.object.id).first()
files = request.FILES.getlist('images') files = request.FILES.getlist('images')
if request.user.is_authenticated() and request.user.is_subscribed: if request.user.is_authenticated() and request.user.is_subscribed:
if self.form.is_valid(): if self.form.is_valid():
self.form.process(parent=parent, owner=request.user, files=files, self.form.process(parent=parent, owner=request.user, files=files,
automodere=request.user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID)) automodere=request.user.is_in_group(settings.SITH_GROUP_SAS_ADMIN_ID))
if self.form.is_valid(): if self.form.is_valid():
return super(AlbumView, self).form_valid(self.form) return super(AlbumView, self).form_valid(self.form)
else: else:
@ -239,6 +242,7 @@ class AlbumView(CanViewMixin, DetailView, FormMixin):
# Admin views # Admin views
class ModerationView(TemplateView): class ModerationView(TemplateView):
template_name = "sas/moderation.jinja" template_name = "sas/moderation.jinja"
@ -257,23 +261,26 @@ class ModerationView(TemplateView):
a.save() a.save()
elif 'delete' in request.POST.keys(): elif 'delete' in request.POST.keys():
a.delete() a.delete()
except: pass except:
pass
return super(ModerationView, self).get(request, *args, **kwargs) return super(ModerationView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
kwargs = super(ModerationView, self).get_context_data(**kwargs) kwargs = super(ModerationView, self).get_context_data(**kwargs)
kwargs['albums_to_moderate'] = Album.objects.filter(is_moderated=False, is_in_sas=True, kwargs['albums_to_moderate'] = Album.objects.filter(is_moderated=False, is_in_sas=True,
is_folder=True).order_by('id') is_folder=True).order_by('id')
kwargs['pictures'] = Picture.objects.filter(is_moderated=False, is_in_sas=True, is_folder=False) kwargs['pictures'] = Picture.objects.filter(is_moderated=False, is_in_sas=True, is_folder=False)
kwargs['albums'] = Album.objects.filter(id__in=kwargs['pictures'].values('parent').distinct('parent')) kwargs['albums'] = Album.objects.filter(id__in=kwargs['pictures'].values('parent').distinct('parent'))
return kwargs return kwargs
class PictureEditForm(forms.ModelForm): class PictureEditForm(forms.ModelForm):
class Meta: class Meta:
model = Picture model = Picture
fields=['name', 'parent'] fields = ['name', 'parent']
parent = make_ajax_field(Picture, 'parent', 'files', help_text="") parent = make_ajax_field(Picture, 'parent', 'files', help_text="")
class AlbumEditForm(forms.ModelForm): class AlbumEditForm(forms.ModelForm):
class Meta: class Meta:
model = Album model = Album
@ -283,16 +290,18 @@ class AlbumEditForm(forms.ModelForm):
edit_groups = make_ajax_field(Album, 'edit_groups', 'groups', help_text="") edit_groups = make_ajax_field(Album, 'edit_groups', 'groups', help_text="")
recursive = forms.BooleanField(label=_("Apply rights recursively"), required=False) recursive = forms.BooleanField(label=_("Apply rights recursively"), required=False)
class PictureEditView(CanEditMixin, UpdateView): class PictureEditView(CanEditMixin, UpdateView):
model=Picture model = Picture
form_class=PictureEditForm form_class = PictureEditForm
template_name='core/edit.jinja' template_name = 'core/edit.jinja'
pk_url_kwarg = "picture_id" pk_url_kwarg = "picture_id"
class AlbumEditView(CanEditMixin, UpdateView): class AlbumEditView(CanEditMixin, UpdateView):
model=Album model = Album
form_class=AlbumEditForm form_class = AlbumEditForm
template_name='core/edit.jinja' template_name = 'core/edit.jinja'
pk_url_kwarg = "album_id" pk_url_kwarg = "album_id"
def form_valid(self, form): def form_valid(self, form):
@ -300,4 +309,3 @@ class AlbumEditView(CanEditMixin, UpdateView):
if form.cleaned_data['recursive']: if form.cleaned_data['recursive']:
self.object.apply_rights_recursively(True) self.object.apply_rights_recursively(True)
return ret return ret