cover images; sorl>=10; hook sponsors off sorl
[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 time
6 from StringIO import StringIO
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
9 from django.template.loader import render_to_string
10 from PIL import Image
11
12 from sponsors.fields import JSONField
13 from django.core.files.base import ContentFile
14
15 THUMB_WIDTH=120
16 THUMB_HEIGHT=120
17
18 class Sponsor(models.Model):
19     name = models.CharField(_('name'), max_length=120)
20     _description = models.CharField(_('description'), blank=True, max_length=255)
21     logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
22     url = models.URLField(_('url'), blank=True, verify_exists=False)
23
24     def __unicode__(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(_('name'), max_length=120)
36     sponsors = JSONField(_('sponsors'), default={})
37     _html = models.TextField(blank=True, editable=False)
38     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
39
40     def populated_sponsors(self):
41         result = []
42         offset = 0
43         for column in self.get_sponsors_value():
44             result_group = {'name': column['name'], 'sponsors': []}
45             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
46             for sponsor_pk in column['sponsors']:
47                 try:
48                     result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
49                     offset -= THUMB_HEIGHT
50                 except KeyError:
51                     pass
52             result.append(result_group)
53         return result
54
55     def render_sprite(self):
56         sponsor_ids = []
57         for column in self.get_sponsors_value():
58             sponsor_ids.extend(column['sponsors'])
59         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
60         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors)*THUMB_HEIGHT))
61         for i, sponsor_id in enumerate(sponsor_ids):
62             simg = Image.open(sponsors[sponsor_id].logo.path)
63             if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
64                 size = (
65                     min(THUMB_WIDTH, 
66                         simg.size[0] * THUMB_HEIGHT / simg.size[1]),
67                     min(THUMB_HEIGHT,
68                         simg.size[1] * THUMB_WIDTH / simg.size[0])
69                 )
70                 simg = simg.resize(size, Image.ANTIALIAS)
71             sprite.paste(simg, (
72                     (THUMB_WIDTH - simg.size[0]) / 2,
73                     i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
74                     ))
75         imgstr = StringIO()
76         sprite.save(imgstr, 'png')
77
78         if self.sprite:
79             self.sprite.delete(save=False)
80         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
81
82     def html(self):
83         return self._html
84     html = property(fget=html)
85
86     def save(self, *args, **kwargs):
87         self.render_sprite()
88         self._html = render_to_string('sponsors/page.html', {
89             'sponsors': self.populated_sponsors(),
90             'page': self
91         })
92         return super(SponsorPage, self).save(*args, **kwargs)
93
94     def __unicode__(self):
95         return self.name
96