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.
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
12 from jsonfield import JSONField
13 from django.core.files.base import ContentFile
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)
25 def __unicode__(self):
28 def description(self):
29 if len(self._description):
30 return self._description
35 class SponsorPage(models.Model):
36 name = models.CharField(_('name'), max_length=120)
37 sponsors = JSONField(_('sponsors'), default={})
38 _html = models.TextField(blank=True, editable=False)
39 sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
41 def populated_sponsors(self):
44 for column in self.sponsors:
45 result_group = {'name': column['name'], 'sponsors': []}
46 sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
47 for sponsor_pk in column['sponsors']:
49 result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
50 offset -= THUMB_HEIGHT
53 result.append(result_group)
56 def render_sprite(self):
58 for column in self.sponsors:
59 sponsor_ids.extend(column['sponsors'])
60 sponsors = Sponsor.objects.in_bulk(sponsor_ids)
61 sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
62 for i, sponsor_id in enumerate(sponsor_ids):
63 simg = Image.open(sponsors[sponsor_id].logo.path)
64 if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
67 simg.size[0] * THUMB_HEIGHT / simg.size[1]),
69 simg.size[1] * THUMB_WIDTH / simg.size[0])
71 simg = simg.resize(size, Image.ANTIALIAS)
73 (THUMB_WIDTH - simg.size[0]) / 2,
74 i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
77 sprite.save(imgstr, 'png')
80 self.sprite.delete(save=False)
81 self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
85 html = property(fget=html)
87 def save(self, *args, **kwargs):
89 self._html = render_to_string('sponsors/page.html', {
90 'sponsors': self.populated_sponsors(),
93 return super(SponsorPage, self).save(*args, **kwargs)
95 def __unicode__(self):