add option to generate covers with non-standard aspect ratio
[wolnelektury.git] / src / 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 json
6 import time
7 from StringIO import StringIO
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
10 from django.template.loader import render_to_string
11 from PIL import Image
12
13 from jsonfield import JSONField
14 from django.core.files.base import ContentFile
15 from ssify import flush_ssi_includes
16
17 THUMB_WIDTH = 120
18 THUMB_HEIGHT = 120
19
20
21 class Sponsor(models.Model):
22     name = models.CharField(_('name'), max_length=120)
23     _description = models.CharField(_('description'), blank=True, max_length=255)
24     logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
25     url = models.URLField(_('url'), blank=True)
26
27     def __unicode__(self):
28         return self.name
29
30     def description(self):
31         if len(self._description):
32             return self._description
33         else:
34             return self.name
35
36
37 class SponsorPage(models.Model):
38     name = models.CharField(_('name'), max_length=120)
39     sponsors = JSONField(_('sponsors'), default={})
40     _html = models.TextField(blank=True, editable=False)
41     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
42
43     def populated_sponsors(self):
44         result = []
45         offset = 0
46         for column in self.sponsors:
47             result_group = {'name': column['name'], 'sponsors': []}
48             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
49             for sponsor_pk in column['sponsors']:
50                 try:
51                     result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
52                     offset -= THUMB_HEIGHT
53                 except KeyError:
54                     pass
55             result.append(result_group)
56         return result
57
58     def render_sprite(self):
59         sponsor_ids = []
60         for column in self.sponsors:
61             sponsor_ids.extend(column['sponsors'])
62         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
63         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
64         for i, sponsor_id in enumerate(sponsor_ids):
65             simg = Image.open(sponsors[sponsor_id].logo.path)
66             if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
67                 size = (
68                     min(THUMB_WIDTH,
69                         simg.size[0] * THUMB_HEIGHT / simg.size[1]),
70                     min(THUMB_HEIGHT,
71                         simg.size[1] * THUMB_WIDTH / simg.size[0])
72                 )
73                 simg = simg.resize(size, Image.ANTIALIAS)
74             sprite.paste(simg, (
75                     (THUMB_WIDTH - simg.size[0]) / 2,
76                     i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
77                     ))
78         imgstr = StringIO()
79         sprite.save(imgstr, 'png')
80
81         if self.sprite:
82             self.sprite.delete(save=False)
83         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (
84             self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
85
86     def html(self):
87         return self._html
88     html = property(fget=html)
89
90     def save(self, *args, **kwargs):
91         if isinstance(self.sponsors, basestring):
92             # Walkaround for weird jsonfield 'no-decode' optimization.
93             self.sponsors = json.loads(self.sponsors)
94         self.render_sprite()
95         self._html = render_to_string('sponsors/page.html', {
96             'sponsors': self.populated_sponsors(),
97             'page': self
98         })
99         ret = super(SponsorPage, self).save(*args, **kwargs)
100         self.flush_includes()
101         return ret
102
103     def flush_includes(self):
104         flush_ssi_includes(['/sponsors/page/%s.html' % self.name])
105
106     def __unicode__(self):
107         return self.name