update librarian
[redakcja.git] / apps / cover / models.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from django.core.files.base import ContentFile
7 from django.core.files.storage import FileSystemStorage
8 from django.db import models
9 from django.db.models.signals import post_save
10 from django.dispatch import receiver
11 from django.utils.translation import ugettext_lazy as _
12 from django.contrib.sites.models import Site
13 from cover.utils import URLOpener
14
15
16 class OverwriteStorage(FileSystemStorage):
17
18     def get_available_name(self, name, max_length=None):
19         self.delete(name)
20         return name
21
22
23 class Image(models.Model):
24     title = models.CharField(max_length=255, verbose_name=_('title'))
25     author = models.CharField(max_length=255, verbose_name=_('author'))
26     license_name = models.CharField(max_length=255, verbose_name=_('license name'))
27     license_url = models.URLField(max_length=255, blank=True, verbose_name=_('license URL'))
28     source_url = models.URLField(verbose_name=_('source URL'), null=True, blank=True)
29     download_url = models.URLField(unique=True, verbose_name=_('image download URL'), null=True, blank=True)
30     file = models.ImageField(
31         upload_to='cover/image', storage=OverwriteStorage(), editable=True, verbose_name=_('file'))
32
33     class Meta:
34         verbose_name = _('cover image')
35         verbose_name_plural = _('cover images')
36
37     def __unicode__(self):
38         return u"%s - %s" % (self.author, self.title)
39
40     @models.permalink
41     def get_absolute_url(self):
42         return 'cover_image', [self.id]
43
44     def get_full_url(self):
45         return "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
46
47
48 @receiver(post_save, sender=Image)
49 def download_image(sender, instance, **kwargs):
50     if instance.pk and not instance.file:
51         t = URLOpener().open(instance.download_url).read()
52         instance.file.save("%d.jpg" % instance.pk, ContentFile(t))