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 django import template
6 from django.utils.functional import lazy
7 from django.utils.cache import add_never_cache_headers
8 from catalogue.models import Book, Fragment
9 from social.utils import likes, get_or_choose_cite, choose_cite as cs
10 from ..models import Carousel, Cite
12 register = template.Library()
15 @register.simple_tag(takes_context=True)
16 def likes_book(context, book):
17 request = context['request']
18 return likes(request.user, book, request)
21 @register.simple_tag(takes_context=True)
22 def choose_cite(context, book_id=None, tag_ids=None):
23 request = context['request']
24 return get_or_choose_cite(request, book_id, tag_ids)
28 def choose_cites(number, book=None, author=None):
30 return book.choose_fragments(number) # todo: cites?
31 elif author is not None:
32 return Fragment.tagged.with_all([author]).order_by('?')[:number]
35 @register.simple_tag(takes_context=True)
36 def book_shelf_tags(context, book_id):
37 request = context['request']
38 if not request.user.is_authenticated:
40 book = Book.objects.get(pk=book_id)
41 lks = likes(request.user, book, request)
46 tags = book.tags.filter(category='set', user=request.user).exclude(name='')
50 return template.loader.render_to_string('social/shelf_tags.html', ctx)
51 return lazy(get_value, str)()
54 @register.inclusion_tag('social/carousel.html', takes_context=True)
55 def carousel(context, placement):
56 carousel = Carousel.get(placement)
59 for item in carousel.carouselitem_set.all().select_related('banner')
62 request = context['request']
63 if 'banner' in request.GET:
65 banner_id = int(request.GET['banner'])
66 except (TypeError, ValueError):
70 index = [b.pk for b in banners].index(banner_id)
72 if request.user.is_staff:
73 # Staff is allowed to preview any banner.
75 banners.insert(0, Cite.objects.get(pk=banner_id))
76 except Cite.DoesNotExist:
79 # Put selected banner to front.
80 banners = [banners[index]] + banners[:index] + banners[index+1:]
88 @register.inclusion_tag('social/carousel_2022.html', takes_context=True)
89 def carousel_2022(context, placement):
90 banners = Carousel.get(placement).carouselitem_set.all()#first().get_banner()
92 'banners': [b.get_banner() for b in banners],
96 @register.inclusion_tag('social/embed_video.html')
98 m = re.match(r'https://www.youtube.com/watch\?v=([^&;]+)', url)
100 'youtube_id': m.group(1) if m else None,