856ed9ae73a2297e0236666ef7b642c85b68a2ab
[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.template.loader import render_to_string
10 from PIL import Image
11
12 from django.core.files.base import ContentFile
13
14 THUMB_WIDTH = 120
15 THUMB_HEIGHT = 120
16
17
18 class Sponsor(models.Model):
19     name = models.CharField('nazwa', max_length=120)
20     _description = models.CharField('opis', blank=True, max_length=255)
21     logo = models.ImageField('logo', upload_to='sponsorzy/sponsor/logo')
22     url = models.URLField('url', blank=True)
23
24     def __str__(self):
25         return self.name
26
27     def description(self):
28         if len(self._description):
29             return self._description
30         else:
31             return self.name
32
33
34 class SponsorPage(models.Model):
35     name = models.CharField('nazwa', max_length=120)
36     sponsors = models.TextField('sponsorzy', default='{}')
37     _html = models.TextField(blank=True, editable=False)
38     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
39
40     def get_sponsors_json(self):
41         return json.loads(self.sponsors or '[]')
42
43     def populated_sponsors(self):
44         result = []
45         offset = 0
46         for column in self.get_sponsors_json():
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             if result_group['sponsors']:
56                 result.append(result_group)
57         return result
58
59     def render_sprite(self):
60         sponsor_ids = []
61         for column in self.get_sponsors_json():
62             sponsor_ids.extend(column['sponsors'])
63         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
64         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
65         for i, sponsor_id in enumerate(sponsor_ids):
66             simg = Image.open(sponsors[sponsor_id].logo.path)
67             if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
68                 size = (
69                     min(THUMB_WIDTH,
70                         round(simg.size[0] * THUMB_HEIGHT / simg.size[1])),
71                     min(THUMB_HEIGHT,
72                         round(simg.size[1] * THUMB_WIDTH / simg.size[0]))
73                 )
74                 simg = simg.resize(size, Image.ANTIALIAS)
75             sprite.paste(simg, (
76                     round((THUMB_WIDTH - simg.size[0]) / 2),
77                     round(i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2),
78                     ))
79         imgstr = BytesIO()
80         sprite.save(imgstr, 'png')
81
82         if self.sprite:
83             self.sprite.delete(save=False)
84         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (
85             self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
86
87     def html(self):
88         return self._html
89     html = property(fget=html)
90
91     def save(self, *args, **kwargs):
92         self.render_sprite()
93         self._html = render_to_string('sponsors/page.html', {
94             'sponsors': self.populated_sponsors(),
95             'page': self
96         })
97         ret = super(SponsorPage, self).save(*args, **kwargs)
98         cache.delete('sponsor_page:' + self.name)
99         return ret
100
101     def __str__(self):
102         return self.name