Fixes.
[wolnelektury.git] / src / sponsors / models.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 import time
6 from io import BytesIO
7 from django.core.cache import cache
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
16 THUMB_WIDTH = 120
17 THUMB_HEIGHT = 120
18
19
20 class Sponsor(models.Model):
21     name = models.CharField(_('name'), max_length=120)
22     _description = models.CharField(_('description'), blank=True, max_length=255)
23     logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
24     url = models.URLField(_('url'), blank=True)
25
26     def __str__(self):
27         return self.name
28
29     def description(self):
30         if len(self._description):
31             return self._description
32         else:
33             return self.name
34
35
36 class SponsorPage(models.Model):
37     name = models.CharField(_('name'), max_length=120)
38     sponsors = JSONField(_('sponsors'), default={})
39     _html = models.TextField(blank=True, editable=False)
40     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
41
42     def populated_sponsors(self):
43         result = []
44         offset = 0
45         for column in self.sponsors:
46             result_group = {'name': column['name'], 'sponsors': []}
47             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
48             for sponsor_pk in column['sponsors']:
49                 try:
50                     result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
51                     offset -= THUMB_HEIGHT
52                 except KeyError:
53                     pass
54             result.append(result_group)
55         return result
56
57     def render_sprite(self):
58         sponsor_ids = []
59         for column in self.sponsors:
60             sponsor_ids.extend(column['sponsors'])
61         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
62         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
63         for i, sponsor_id in enumerate(sponsor_ids):
64             simg = Image.open(sponsors[sponsor_id].logo.path)
65             if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
66                 size = (
67                     min(THUMB_WIDTH,
68                         round(simg.size[0] * THUMB_HEIGHT / simg.size[1])),
69                     min(THUMB_HEIGHT,
70                         round(simg.size[1] * THUMB_WIDTH / simg.size[0]))
71                 )
72                 simg = simg.resize(size, Image.ANTIALIAS)
73             sprite.paste(simg, (
74                     round((THUMB_WIDTH - simg.size[0]) / 2),
75                     round(i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2),
76                     ))
77         imgstr = BytesIO()
78         sprite.save(imgstr, 'png')
79
80         if self.sprite:
81             self.sprite.delete(save=False)
82         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (
83             self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
84
85     def html(self):
86         return self._html
87     html = property(fget=html)
88
89     def save(self, *args, **kwargs):
90         if isinstance(self.sponsors, str):
91             # Walkaround for weird jsonfield 'no-decode' optimization.
92             self.sponsors = json.loads(self.sponsors)
93         self.render_sprite()
94         self._html = render_to_string('sponsors/page.html', {
95             'sponsors': self.populated_sponsors(),
96             'page': self
97         })
98         ret = super(SponsorPage, self).save(*args, **kwargs)
99         cache.delete('sponsor_page:' + name)
100         return ret
101
102     def __str__(self):
103         return self.name