a766b44d95096b0d4e261741e2e0454c2df62082
[wolnelektury.git] / src / picture / templatetags / picture_tags.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 logging
6 from random import randint
7 from django import template
8 from django.core.urlresolvers import reverse
9 from django.utils.cache import add_never_cache_headers
10 import sorl.thumbnail.default
11 from ssify import ssi_variable
12 from catalogue.utils import split_tags
13 from ..engine import CustomCroppingEngine
14 from ..models import Picture
15
16
17 register = template.Library()
18
19 cropper = CustomCroppingEngine()
20
21
22 @register.inclusion_tag('picture/picture_wide.html', takes_context=True)
23 def picture_wide(context, picture):
24     context.update({
25         'picture': picture,
26         'main_link': reverse('picture_viewer', args=[picture.slug]),
27         'request': context.get('request'),
28         'tags': split_tags(picture.tags),
29         })
30     return context
31
32
33 @register.simple_tag()
34 def area_thumbnail_url(area, geometry):
35     def to_square(coords):
36         w = coords[1][0] - coords[0][0]
37         h = coords[1][1] - coords[0][1]
38         if w == h:
39             return coords
40         elif w > h:
41             return [[coords[0][0] + w/2 - h/2, coords[0][1]],
42                     [coords[1][0] - w/2 + h/2, coords[1][1]]]
43         else:
44             return [[coords[0][0], coords[0][1] + h/2 - w/2],
45                     [coords[1][0], coords[1][1] - h/2 + w/2, ]]
46
47     # so much for sorl extensibility.
48     # what to do about this?
49     _engine = sorl.thumbnail.default.engine
50     sorl.thumbnail.default.engine = cropper
51     coords = to_square(area.area)
52
53     try:
54         th = sorl.thumbnail.default.backend.get_thumbnail(
55             area.picture.image_file,
56             geometry,
57             crop="%dpx %dpx %dpx %dpx" % tuple(map(lambda d: max(0, d), tuple(coords[0] + coords[1]))))
58     except ZeroDivisionError:
59         return ''
60     except Exception, e:
61         logging.exception("Error creating a thumbnail for PictureArea")
62         return ''
63
64     sorl.thumbnail.default.engine = _engine
65
66     return th.url
67
68
69 @ssi_variable(register, patch_response=[add_never_cache_headers])
70 def picture_random_picture(request, exclude_ids, unless=None):
71     if unless:
72         return None
73     queryset = Picture.objects.exclude(pk__in=exclude_ids).exclude(image_file='')
74     count = queryset.count()
75     if count:
76         return queryset[randint(0, count - 1)].pk
77     else:
78         return None