484b52ecb3c4f13c974d1dd9d255d0f811061bf4
[wolnelektury.git] / src / social / templatetags / social_tags.py
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.
4 #
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
15
16 register = template.Library()
17
18
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)
22
23
24 def choose_cite(book_id=None, tag_ids=None):
25     """Choose a cite for main page, for book or for set of tags."""
26     if book_id is not None:
27         cites = Cite.objects.filter(Q(book=book_id) | Q(book__ancestor=book_id))
28     elif tag_ids is not None:
29         tags = Tag.objects.filter(pk__in=tag_ids)
30         cites = cites_for_tags(tags)
31     else:
32         cites = Cite.objects.all()
33     stickies = cites.filter(sticky=True)
34     count = stickies.count()
35     if count:
36         cite = stickies[randint(0, count - 1)]
37     else:
38         count = cites.count()
39         if count:
40             cite = cites[randint(0, count - 1)]
41         else:
42             cite = None
43     return cite
44
45
46 @ssi_variable(register, name='choose_cite', patch_response=[add_never_cache_headers])
47 def choose_cite_tag(request, book_id=None, tag_ids=None):
48     try:
49         assert request.user.is_staff
50         assert 'choose_cite' in request.GET
51         cite = Cite.objects.get(pk=request.GET['choose_cite'])
52     except (AssertionError, Cite.DoesNotExist):
53         cite = choose_cite(book_id, tag_ids)
54     return cite.pk if cite is not None else None
55
56
57 @register.inclusion_tag('social/cite_promo.html')
58 def render_cite(cite):
59     return {
60         'cite': cite,
61     }
62
63
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():
67         return None
68     book = Book.objects.get(pk=book_id)
69     lks = likes(request.user, book, request)
70
71     def get_value():
72         if not lks:
73             return ''
74         tags = book.tags.filter(category='set', user=request.user).exclude(name='')
75         if not tags:
76             return ''
77         ctx = {'tags': tags}
78         return template.loader.render_to_string('social/shelf_tags.html', ctx)
79     return lazy(get_value, unicode)()