url links to zip packages
[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 sorl.thumbnail.fields import ImageWithThumbnailsField
13 from sponsors.fields import JSONField
14 from django.core.files.base import ContentFile
15
16 THUMB_WIDTH=120
17 THUMB_HEIGHT=120
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 = ImageWithThumbnailsField(
23         _('logo'),
24         upload_to='sponsorzy/sponsor/logo',
25         thumbnail={
26             'size': (THUMB_WIDTH, THUMB_HEIGHT),
27             'extension': 'png',
28             'options': ['pad', 'detail'],
29         })
30     url = models.URLField(_('url'), blank=True, verify_exists=False)
31
32     def __unicode__(self):
33         return self.name
34
35     def description(self):
36         if len(self._description):
37             return self._description
38         else:
39             return self.name
40
41
42 class SponsorPage(models.Model):
43     name = models.CharField(_('name'), max_length=120)
44     sponsors = JSONField(_('sponsors'), default={})
45     _html = models.TextField(blank=True, editable=False)
46     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
47
48     def populated_sponsors(self):
49         result = []
50         offset = 0
51         for column in self.get_sponsors_value():
52             result_group = {'name': column['name'], 'sponsors': []}
53             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
54             for sponsor_pk in column['sponsors']:
55                 try:
56                     result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
57                     offset -= THUMB_HEIGHT
58                 except KeyError:
59                     pass
60             result.append(result_group)
61         return result
62
63     def render_sprite(self):
64         sponsor_ids = []
65         for column in self.get_sponsors_value():
66             sponsor_ids.extend(column['sponsors'])
67         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
68         sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors)*THUMB_HEIGHT))
69         for i, sponsor_id in enumerate(sponsor_ids):
70             simg = Image.open(sponsors[sponsor_id].logo.thumbnail.dest)
71             sprite.paste(simg, (0, i*THUMB_HEIGHT))
72         imgstr = StringIO()
73         sprite.save(imgstr, 'png')
74
75         if self.sprite:
76             self.sprite.delete(save=False)
77         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
78
79     def html(self):
80         return self._html
81     html = property(fget=html)
82
83     def save(self, *args, **kwargs):
84         self.render_sprite()
85         self._html = render_to_string('sponsors/page.html', {
86             'sponsors': self.populated_sponsors(),
87             'page': self
88         })
89         return super(SponsorPage, self).save(*args, **kwargs)
90
91     def __unicode__(self):
92         return self.name
93