closes #2043: covers in ebooks
[wolnelektury.git] / apps / sponsors / models.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import time
6 from StringIO import StringIO
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
9 from django.template.loader import render_to_string
10 from PIL import Image
11
12 from jsonfield import JSONField
13 from django.core.files.base import ContentFile
14
15 THUMB_WIDTH = 120
16 THUMB_HEIGHT = 120
17
18
19 class Sponsor(models.Model):
20     name = models.CharField(_('name'), max_length=120)
21     _description = models.CharField(_('description'), blank=True, max_length=255)
22     logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
23     url = models.URLField(_('url'), blank=True, verify_exists=False)
24
25     def __unicode__(self):
26         return self.name
27
28     def description(self):
29         if len(self._description):
30             return self._description
31         else:
32             return self.name
33
34
35 class SponsorPage(models.Model):
36     name = models.CharField(_('name'), max_length=120)
37     sponsors = JSONField(_('sponsors'), default={})
38     _html = models.TextField(blank=True, editable=False)
39     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
40
41     def populated_sponsors(self):
42         result = []
43         offset = 0
44         for column in self.sponsors:
45             result_group = {'name': column['name'], 'sponsors': []}
46             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
47             for sponsor_pk in column['sponsors']:
48                 try:
49                     result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
50                     offset -= THUMB_HEIGHT
51                 except KeyError:
52                     pass
53             result.append(result_group)
54         return result
55
56     def render_sprite(self):
57         sponsor_ids = []
58         for column in self.sponsors:
59             sponsor_ids.extend(column['sponsors'])
60         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
61         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
62         for i, sponsor_id in enumerate(sponsor_ids):
63             simg = Image.open(sponsors[sponsor_id].logo.path)
64             if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
65                 size = (
66                     min(THUMB_WIDTH, 
67                         simg.size[0] * THUMB_HEIGHT / simg.size[1]),
68                     min(THUMB_HEIGHT,
69                         simg.size[1] * THUMB_WIDTH / simg.size[0])
70                 )
71                 simg = simg.resize(size, Image.ANTIALIAS)
72             sprite.paste(simg, (
73                     (THUMB_WIDTH - simg.size[0]) / 2,
74                     i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
75                     ))
76         imgstr = StringIO()
77         sprite.save(imgstr, 'png')
78
79         if self.sprite:
80             self.sprite.delete(save=False)
81         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
82
83     def html(self):
84         return self._html
85     html = property(fget=html)
86
87     def save(self, *args, **kwargs):
88         self.render_sprite()
89         self._html = render_to_string('sponsors/page.html', {
90             'sponsors': self.populated_sponsors(),
91             'page': self
92         })
93         return super(SponsorPage, self).save(*args, **kwargs)
94
95     def __unicode__(self):
96         return self.name
97