1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
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
15 register = template.Library()
17 cropper = CustomCroppingEngine()
20 @register.inclusion_tag('picture/picture_wide.html', takes_context=True)
21 def picture_wide(context, picture):
24 'main_link': reverse('picture_viewer', args=[picture.slug]),
25 'request': context.get('request'),
26 'tags': split_tags(picture.tags),
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]
39 return [[coords[0][0] + w/2 - h/2, coords[0][1]],
40 [coords[1][0] - w/2 + h/2, coords[1][1]]]
42 return [[coords[0][0], coords[0][1] + h/2 - w/2],
43 [coords[1][0], coords[1][1] - h/2 + w/2, ]]
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)
52 th = sorl.thumbnail.default.backend.get_thumbnail(
53 area.picture.image_file,
55 crop="%dpx %dpx %dpx %dpx" % tuple(map(lambda d: max(0, d), tuple(coords[0] + coords[1]))))
56 except ZeroDivisionError:
58 except Exception as e:
59 logging.exception("Error creating a thumbnail for PictureArea")
62 sorl.thumbnail.default.engine = _engine
68 def picture_random_picture(exclude_ids, unless=None):
71 queryset = Picture.objects.exclude(pk__in=exclude_ids).exclude(image_file='')
72 count = queryset.count()
74 return queryset[randint(0, count - 1)]