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