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