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 django import template
6 from catalogue.models import Book
7 from social.models import Cite
8 from social.utils import likes, cites_for_tags
9
10 register = template.Library()
11
12 register.filter('likes', likes)
13
14
15 @register.assignment_tag(takes_context=True)
16 def choose_cite(context, ctx=None):
17     """Choose a cite for main page, for book or for set of tags."""
18     try:
19         request = context['request']
20         assert request.user.is_staff
21         assert 'choose_cite' in request.GET
22         cite = Cite.objects.get(pk=request.GET['choose_cite'])
23     except AssertionError, Cite.DoesNotExist:
24         if ctx is None:
25             cites = Cite.objects.all()
26         elif isinstance(ctx, Book):
27             cites = ctx.cite_set.all()
28             if not cites.exists():
29                 cites = cites_for_tags([ctx.book_tag()])
30         else:
31             cites = cites_for_tags(ctx)
32         cite = cites.order_by('-sticky', '?')[0] if cites.exists() else None
33     return cite
34
35
36 @register.inclusion_tag('social/cite_promo.html')
37 def render_cite(cite):
38     return {
39         'cite': cite,
40     }
41
42
43 @register.inclusion_tag('social/cite_promo.html', takes_context=True)
44 def cite_promo(context, ctx=None, fallback=False):
45     return {
46         'cite': choose_cite(context, ctx),
47         'fallback': fallback,
48         'ctx': ctx,
49     }
50
51
52 @register.inclusion_tag('social/shelf_tags.html', takes_context=True)
53 def shelf_tags(context, book):
54     user = context['request'].user
55     if not user.is_authenticated():
56         tags = []
57     else:
58         tags = book.tags.filter(category='set', user=user).exclude(name='')
59     return {'tags': tags}