Merge branch 'master' into ofop
[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 import re
7 from urlparse import urljoin
8 from django.conf import settings
9 from django.core.files.base import ContentFile
10 from django.db import models
11 from django.db.models.signals import post_save
12 from django.dispatch import receiver
13 from django.utils.translation import ugettext_lazy as _
14 from django.contrib.sites.models import Site
15 from cover.utils import URLOpener
16
17
18 class Image(models.Model):
19     title = models.CharField(max_length=255, verbose_name=_('title'))
20     author = models.CharField(max_length=255, verbose_name=_('author'))
21     license_name = models.CharField(max_length=255, verbose_name=_('license name'))
22     license_url = models.URLField(max_length=255, blank=True, verbose_name=_('license URL'))
23     source_url = models.URLField(verbose_name=_('source URL'))
24     download_url = models.URLField(unique=True, verbose_name=_('image download URL'))
25     file = models.ImageField(upload_to='cover/image', editable=False, verbose_name=_('file'))
26
27     class Meta:
28         verbose_name = _('cover image')
29         verbose_name_plural = _('cover images')
30
31     def __unicode__(self):
32         return u"%s - %s" % (self.author, self.title)
33
34     @models.permalink
35     def get_absolute_url(self):
36         return ('cover_image', [self.id])
37
38     def get_full_url(self):
39         return "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
40
41
42 @receiver(post_save, sender=Image)
43 def download_image(sender, instance, **kwargs):
44     if instance.pk and not instance.file:
45         t = URLOpener().open(instance.download_url).read()
46         instance.file.save("%d.jpg" % instance.pk, ContentFile(t))
47         
48