1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django.core.files.base import ContentFile
6 from django.core.files.storage import FileSystemStorage
7 from django.db import models
8 from django.db.models.signals import post_save
9 from django.dispatch import receiver
10 from django.urls import reverse
11 from django.utils.translation import ugettext_lazy as _
12 from django.contrib.sites.models import Site
13 from PIL import Image as PILImage
14 from cover.utils import URLOpener
17 class OverwriteStorage(FileSystemStorage):
19 def get_available_name(self, name, max_length=None):
24 class Image(models.Model):
25 title = models.CharField(max_length=255, verbose_name=_('title'))
26 author = models.CharField(max_length=255, verbose_name=_('author'))
27 license_name = models.CharField(max_length=255, verbose_name=_('license name'))
28 license_url = models.URLField(max_length=255, blank=True, verbose_name=_('license URL'))
29 source_url = models.URLField(verbose_name=_('source URL'), null=True, blank=True)
30 download_url = models.URLField(max_length=4096, unique=True, verbose_name=_('image download URL'), null=True, blank=True)
31 file = models.ImageField(
32 upload_to='cover/image',
33 storage=OverwriteStorage(),
34 verbose_name=_('file')
36 use_file = models.ImageField(
37 upload_to='cover/use',
38 storage=OverwriteStorage(),
40 verbose_name=_('file for use')
42 cut_top = models.IntegerField(default=0, )
43 cut_bottom = models.IntegerField(default=0)
44 cut_left = models.IntegerField(default=0)
45 cut_right = models.IntegerField(default=0)
48 verbose_name = _('cover image')
49 verbose_name_plural = _('cover images')
52 return u"%s - %s" % (self.author, self.title)
54 def save(self, **kwargs):
55 super().save(**kwargs)
57 if self.cut_top or self.cut_bottom or self.cut_left or self.cut_right:
58 img = PILImage.open(img)
62 img.size[0] - self.cut_right,
63 img.size[1] - self.cut_bottom,
70 img = ContentFile(buffer.getvalue())
76 super().save(**kwargs)
78 def get_absolute_url(self):
79 return reverse('cover_image', args=[self.id])
81 def get_full_url(self):
82 return "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
85 @receiver(post_save, sender=Image)
86 def download_image(sender, instance, **kwargs):
87 if instance.pk and not instance.file:
88 t = URLOpener().open(instance.download_url).read()
89 instance.file.save("%d.jpg" % instance.pk, ContentFile(t))