7065467b44a0932db7b5f9b0b427c194a0fab789
[wolnelektury.git] / apps / 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(request, book_id=None, tag_ids=None):
25     """Choose a cite for main page, for book or for set of tags."""
26     try:
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)
36         else:
37             cites = Cite.objects.all()
38         stickies = cites.filter(sticky=True)
39         count = stickies.count()
40         if count:
41             cite = stickies[randint(0, count - 1)]
42         else:
43             count = cites.count()
44             if count:
45                 cite = cites[randint(0, count - 1)]
46             else:
47                 cite = None
48     return cite
49
50
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
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     def get_value():
71         if not lks:
72             return ''
73         tags = book.tags.filter(category='set', user=request.user).exclude(name='')
74         if not tags:
75             return ''
76         ctx = {'tags': tags}
77         return template.loader.render_to_string('social/shelf_tags.html', ctx)
78     return lazy(get_value, unicode)()