Merge branch 'master' into sunburnt
[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 import template
7 from catalogue.models import Book
8 from social.models import Cite
9 from social.utils import likes, cites_for_tags
10
11 register = template.Library()
12
13 register.filter('likes', likes)
14
15
16 @register.assignment_tag(takes_context=True)
17 def choose_cite(context, ctx=None):
18     """Choose a cite for main page, for book or for set of tags."""
19     try:
20         request = context['request']
21         assert request.user.is_staff
22         assert 'choose_cite' in request.GET
23         cite = Cite.objects.get(pk=request.GET['choose_cite'])
24     except AssertionError, Cite.DoesNotExist:
25         if ctx is None:
26             cites = Cite.objects.all()
27         elif isinstance(ctx, Book):
28             cites = ctx.cite_set.all()
29             if not cites.exists():
30                 cites = cites_for_tags([ctx.book_tag()])
31         else:
32             cites = cites_for_tags(ctx)
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 @register.inclusion_tag('social/cite_promo.html')
47 def render_cite(cite):
48     return {
49         'cite': cite,
50     }
51
52
53 @register.inclusion_tag('social/cite_promo.html', takes_context=True)
54 def cite_promo(context, ctx=None, fallback=False):
55     return {
56         'cite': choose_cite(context, ctx),
57         'fallback': fallback,
58         'ctx': ctx,
59     }
60
61
62 @register.inclusion_tag('social/shelf_tags.html', takes_context=True)
63 def shelf_tags(context, book):
64     user = context['request'].user
65     if not user.is_authenticated():
66         tags = []
67     else:
68         tags = book.tags.filter(category='set', user=user).exclude(name='')
69     return {'tags': tags}