Fundraising in PDF.
[wolnelektury.git] / src / picture / templatetags / picture_tags.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. 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.simple_tag()
21 def area_thumbnail_url(area, geometry):
22     def to_square(coords):
23         w = coords[1][0] - coords[0][0]
24         h = coords[1][1] - coords[0][1]
25         if w == h:
26             return coords
27         elif w > h:
28             return [[coords[0][0] + w/2 - h/2, coords[0][1]],
29                     [coords[1][0] - w/2 + h/2, coords[1][1]]]
30         else:
31             return [[coords[0][0], coords[0][1] + h/2 - w/2],
32                     [coords[1][0], coords[1][1] - h/2 + w/2, ]]
33
34     # so much for sorl extensibility.
35     # what to do about this?
36     _engine = sorl.thumbnail.default.engine
37     sorl.thumbnail.default.engine = cropper
38     coords = to_square(area.get_area_json())
39
40     try:
41         th = sorl.thumbnail.default.backend.get_thumbnail(
42             area.picture.image_file,
43             geometry,
44             crop="%dpx %dpx %dpx %dpx" % tuple(map(lambda d: max(0, d), tuple(coords[0] + coords[1]))))
45     except ZeroDivisionError:
46         return ''
47     except Exception as e:
48         logging.exception("Error creating a thumbnail for PictureArea")
49         return ''
50
51     sorl.thumbnail.default.engine = _engine
52
53     return th.url
54
55
56 @register.simple_tag
57 def picture_random_picture(exclude_ids):
58     queryset = Picture.objects.exclude(pk__in=exclude_ids).exclude(image_file='')
59     count = queryset.count()
60     if count:
61         return queryset[randint(0, count - 1)]
62     else:
63         return None