1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from random import randint
6 from django.db.models import Q
7 from django import template
8 from django.utils.functional import lazy
9 from django.utils.cache import add_never_cache_headers
10 from catalogue.models import Book, Tag
11 from ssify import ssi_variable
12 from ssify.utils import ssi_vary_on_cookie
13 from social.models import Cite
14 from social.utils import likes, cites_for_tags
16 register = template.Library()
19 @ssi_variable(register, patch_response=[ssi_vary_on_cookie])
20 def likes_book(request, book_id):
21 return likes(request.user, Book.objects.get(pk=book_id), request)
24 def choose_cite(request, book_id=None, tag_ids=None):
25 """Choose a cite for main page, for book or for set of tags."""
27 assert request.user.is_staff
28 assert 'choose_cite' in request.GET
29 cite = Cite.objects.get(pk=request.GET['choose_cite'])
30 except (AssertionError, Cite.DoesNotExist):
31 if book_id is not None:
32 cites = Cite.objects.filter(Q(book=book_id) | Q(book__ancestor=book_id))
33 elif tag_ids is not None:
34 tags = Tag.objects.filter(pk__in=tag_ids)
35 cites = cites_for_tags(tags)
37 cites = Cite.objects.all()
38 stickies = cites.filter(sticky=True)
39 count = stickies.count()
41 cite = stickies[randint(0, count - 1)]
45 cite = cites[randint(0, count - 1)]
51 @ssi_variable(register, name='choose_cite', patch_response=[add_never_cache_headers])
52 def choose_cite_tag(request, book_id=None, tag_ids=None):
53 cite = choose_cite(request, book_id, tag_ids)
54 return cite.pk if cite is not None else None
57 @register.inclusion_tag('social/cite_promo.html')
58 def render_cite(cite):
64 @ssi_variable(register, patch_response=[ssi_vary_on_cookie])
65 def book_shelf_tags(request, book_id):
66 if not request.user.is_authenticated():
68 book = Book.objects.get(pk=book_id)
69 lks = likes(request.user, book, request)
73 tags = book.tags.filter(category='set', user=request.user).exclude(name='')
77 return template.loader.render_to_string('social/shelf_tags.html', ctx)
78 return lazy(get_value, unicode)()