9e7df0c52e0b13ed405bb73a0c4b8b27e171ea45
[django-sponsors.git] / sponsors / models.py
1 # -*- coding: utf-8 -*-
2 # This file is part of django-sponsors, 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.conf import settings
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 = getattr(settings, 'SPONSORS_THUMB_WIDTH', 120)
17 THUMB_HEIGHT = getattr(settings, 'SPONSORS_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     def size(self):
36         width, height = THUMB_WIDTH, THUMB_HEIGHT
37         if width is None:
38             simg = Image.open(self.logo.path)
39             width = int(float(simg.size[0]) / simg.size[1] * height)
40         elif height is None:
41             simg = Image.open(self.logo.path)
42             height = int(float(simg.size[1]) / simg.size[0] * width)
43         return width, height
44
45
46 class SponsorPage(models.Model):
47     name = models.CharField(_('name'), max_length=120)
48     sponsors = JSONField(_('sponsors'), default={})
49     _html = models.TextField(blank=True, editable=False)
50     sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
51
52     def populated_sponsors(self):
53         result = []
54         offset = 0
55         for column in self.sponsors:
56             result_group = {'name': column['name'], 'sponsors': []}
57             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
58             for sponsor_pk in column['sponsors']:
59                 try:
60                     sponsor = sponsor_objects[sponsor_pk]
61                 except KeyError:
62                     pass
63                 else:
64                     result_group['sponsors'].append((offset, sponsor))
65                     offset -= sponsor.size()[1]
66             result.append(result_group)
67         return result
68
69     def render_sprite(self):
70         sponsor_ids = []
71         for column in self.sponsors:
72             sponsor_ids.extend(column['sponsors'])
73         sponsors = Sponsor.objects.in_bulk(sponsor_ids)
74         total_width = 0
75         total_height = 0
76         for sponsor in sponsors.values():
77             w, h = sponsor.size()
78             total_width = max(total_width, w)
79             total_height += h
80         sprite = Image.new('RGBA', (total_width, total_height))
81         offset = 0
82         for i, sponsor_id in enumerate(sponsor_ids):
83             sponsor = sponsors[sponsor_id]
84             simg = Image.open(sponsor.logo.path)
85             thumb_size = sponsor.size()
86             # FIXME: This is too complicated now.
87             if simg.size[0] > thumb_size[0] or simg.size[1] > thumb_size[1]:
88                 size = (
89                     min(thumb_size[0], 
90                         simg.size[0] * thumb_size[1] / simg.size[1]),
91                     min(thumb_size[1],
92                         simg.size[1] * thumb_size[0] / simg.size[0])
93                 )
94                 simg = simg.resize(size, Image.ANTIALIAS)
95             sprite.paste(simg, (
96                     (thumb_size[0] - simg.size[0]) / 2,
97                     offset + (thumb_size[1] - simg.size[1]) / 2,
98                     ))
99             offset += thumb_size[1]
100         imgstr = StringIO()
101         sprite.save(imgstr, 'png')
102
103         if self.sprite:
104             self.sprite.delete(save=False)
105         self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
106
107     def html(self):
108         return self._html
109     html = property(fget=html)
110
111     def save(self, *args, **kwargs):
112         self.render_sprite()
113         self._html = render_to_string('sponsors/page.html', {
114             'sponsors': self.populated_sponsors(),
115             'page': self,
116         })
117         return super(SponsorPage, self).save(*args, **kwargs)
118
119     def __unicode__(self):
120         return self.name
121