704b066300c77255925434654c28210a8add2149
[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 gettext_lazy as _
10 from django.template.loader import render_to_string
11 from PIL import Image
12
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)
24
25     def __str__(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 = models.TextField(_('sponsors'), default='{}')
38     _html = models.TextField(blank=True, editable=False)
39     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
40
41     def get_sponsors_json(self):
42         return json.loads(self.sponsors or '[]')
43
44     def populated_sponsors(self):
45         result = []
46         offset = 0
47         for column in self.get_sponsors_json():
48             result_group = {'name': column['name'], 'sponsors': []}
49             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
50             for sponsor_pk in column['sponsors']:
51                 try:
52                     result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
53                     offset -= THUMB_HEIGHT
54                 except KeyError:
55                     pass
56             if result_group['sponsors']:
57                 result.append(result_group)
58         return result
59
60     def render_sprite(self):
61         sponsor_ids = []
62         for column in self.get_sponsors_json():
63             sponsor_ids.extend(column['sponsors'])
64         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
65         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
66         for i, sponsor_id in enumerate(sponsor_ids):
67             simg = Image.open(sponsors[sponsor_id].logo.path)
68             if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
69                 size = (
70                     min(THUMB_WIDTH,
71                         round(simg.size[0] * THUMB_HEIGHT / simg.size[1])),
72                     min(THUMB_HEIGHT,
73                         round(simg.size[1] * THUMB_WIDTH / simg.size[0]))
74                 )
75                 simg = simg.resize(size, Image.ANTIALIAS)
76             sprite.paste(simg, (
77                     round((THUMB_WIDTH - simg.size[0]) / 2),
78                     round(i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2),
79                     ))
80         imgstr = BytesIO()
81         sprite.save(imgstr, 'png')
82
83         if self.sprite:
84             self.sprite.delete(save=False)
85         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (
86             self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
87
88     def html(self):
89         return self._html
90     html = property(fget=html)
91
92     def save(self, *args, **kwargs):
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:' + self.name)
100         return ret
101
102     def __str__(self):
103         return self.name