2d18d1664f32610b6b3cefcef64792762bfd9747
[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 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
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 __unicode__(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                         simg.size[0] * THUMB_HEIGHT / simg.size[1]),
69                     min(THUMB_HEIGHT,
70                         simg.size[1] * THUMB_WIDTH / simg.size[0])
71                 )
72                 simg = simg.resize(size, Image.ANTIALIAS)
73             sprite.paste(simg, (
74                     (THUMB_WIDTH - simg.size[0]) / 2,
75                     i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
76                     ))
77         imgstr = StringIO()
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' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
83
84     def html(self):
85         return self._html
86     html = property(fget=html)
87
88     def save(self, *args, **kwargs):
89         if isinstance(self.sponsors, basestring):
90             # Walkaround for weird jsonfield 'no-decode' optimization.
91             self.sponsors = json.loads(self.sponsors)
92         self.render_sprite()
93         self._html = render_to_string('sponsors/page.html', {
94             'sponsors': self.populated_sponsors(),
95             'page': self
96         })
97         return super(SponsorPage, self).save(*args, **kwargs)
98
99     def __unicode__(self):
100         return self.name
101