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
9 from ssify import ssi_variable
10 from ssify.utils import ssi_vary_on_cookie
11 from social.utils import likes, get_or_choose_cite
12 from ..models import Carousel, Cite
14 register = template.Library()
17 @ssi_variable(register, patch_response=[ssi_vary_on_cookie])
18 def likes_book(request, book_id):
19 return likes(request.user, Book.objects.get(pk=book_id), request)
22 @ssi_variable(register, name='choose_cite', patch_response=[add_never_cache_headers])
23 def choose_cite_tag(request, book_id=None, tag_ids=None):
24 cite = get_or_choose_cite(request, book_id, tag_ids)
25 return cite.pk if cite is not None else None
28 @register.inclusion_tag('social/cite_promo.html')
29 def render_cite(cite):
35 @ssi_variable(register, patch_response=[ssi_vary_on_cookie])
36 def book_shelf_tags(request, book_id):
37 if not request.user.is_authenticated():
39 book = Book.objects.get(pk=book_id)
40 lks = likes(request.user, book, request)
45 tags = book.tags.filter(category='set', user=request.user).exclude(name='')
49 return template.loader.render_to_string('social/shelf_tags.html', ctx)
50 return lazy(get_value, str)()
53 @register.inclusion_tag('social/carousel.html', takes_context=True)
54 def carousel(context, slug):
57 carousel = Carousel.objects.get(slug=slug)
58 except Carousel.DoesNotExist:
59 # TODO: add sanity check for install.
60 carousel = Carousel.objects.create(slug=slug)
63 for item in carousel.carouselitem_set.all().select_related('banner')
66 request = context['request']
67 if 'banner' in request.GET:
69 banner_id = int(request.GET['banner'])
70 except (TypeError, ValueError):
74 index = [b.pk for b in banners].index(banner_id)
76 if request.user.is_staff:
77 # Staff is allowed to preview any banner.
79 banners.insert(0, Cite.objects.get(pk=banner_id))
80 except Cite.DoesNotExist:
83 # Put selected banner to front.
84 banners = [banners[index]] + banners[:index] + banners[index+1:]
92 @register.inclusion_tag('social/embed_video.html')
94 m = re.match(r'https://www.youtube.com/watch\?v=([^&;]+)', url)
96 'youtube_id': m.group(1) if m else None,