Merge branch 'production'
[wolnelektury.git] / apps / catalogue / templatetags / catalogue_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 import feedparser
6 import datetime
7
8 from django import template
9 from django.template import Node, Variable
10 from django.utils.encoding import smart_str
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.db.models import Q
14 from django.conf import settings
15 from django.utils.translation import ugettext as _
16
17
18 register = template.Library()
19
20
21 class RegistrationForm(UserCreationForm):
22     def as_ul(self):
23         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
24         return self._html_output(u'<li>%(errors)s%(label)s %(field)s<span class="help-text">%(help_text)s</span></li>', u'<li>%s</li>', '</li>', u' %s', False)
25
26
27 class LoginForm(AuthenticationForm):
28     def as_ul(self):
29         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
30         return self._html_output(u'<li>%(errors)s%(label)s %(field)s<span class="help-text">%(help_text)s</span></li>', u'<li>%s</li>', '</li>', u' %s', False)
31
32
33 def iterable(obj):
34     try:
35         iter(obj)
36         return True
37     except TypeError:
38         return False
39
40
41 def capfirst(text):
42     try:
43         return '%s%s' % (text[0].upper(), text[1:])
44     except IndexError:
45         return ''
46
47
48
49 def simple_title(tags):
50     title = []
51     for tag in tags:
52         title.append("%s: %s" % (_(tag.category), tag.name))
53     return capfirst(', '.join(title))
54
55
56 def book_stub_title(book):
57     return ', '.join((book.author, book.title))
58
59
60 @register.simple_tag
61 def book_title(book, html_links=False):
62     try:
63         names = list(book.tags.filter(category='author'))
64     except AttributeError:
65         return book_stub_title(book)
66
67     books = []
68     while book:
69         books.append(book)
70         book = book.parent
71     names.extend(reversed(books))
72
73     if html_links:
74         names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
75     else:
76         names = [tag.name for tag in names]
77
78     return ', '.join(names)
79
80
81 @register.simple_tag
82 def book_title_html(book):
83     return book_title(book, html_links=True)
84
85
86 @register.simple_tag
87 def title_from_tags(tags):
88     def split_tags(tags):
89         result = {}
90         for tag in tags:
91             result[tag.category] = tag
92         return result
93
94     # TODO: Remove this after adding flection mechanism
95     return simple_title(tags)
96
97     class Flection(object):
98         def get_case(self, name, flection):
99             return name
100     flection = Flection()
101
102     self = split_tags(tags)
103
104     title = u''
105
106     # Specjalny przypadek oglądania wszystkich lektur na danej półce
107     if len(self) == 1 and 'set' in self:
108         return u'Półka %s' % self['set']
109
110     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
111     # jest wybrana przez użytkownika
112     if 'epoch' in self and len(self) == 1:
113         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
114         return capfirst(text)
115
116     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
117     # są tylko rodzaj literacki i autor
118     if 'kind' in self and 'author' in self and len(self) == 2:
119         text = u'%s w twórczości %s' % (unicode(self['kind']),
120             flection.get_case(unicode(self['author']), u'dopełniacz'))
121         return capfirst(text)
122
123     # Przypadki ogólniejsze
124     if 'theme' in self:
125         title += u'Motyw %s' % unicode(self['theme'])
126
127     if 'genre' in self:
128         if 'theme' in self:
129             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
130         else:
131             title += unicode(self['genre'])
132
133     if 'kind' in self or 'author' in self or 'epoch' in self:
134         if 'genre' in self or 'theme' in self:
135             if 'kind' in self:
136                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
137             else:
138                 title += u' w twórczości '
139         else:
140             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
141
142     if 'author' in self:
143         title += flection.get_case(unicode(self['author']), u'dopełniacz')
144     elif 'epoch' in self:
145         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
146
147     return capfirst(title)
148
149
150 @register.simple_tag
151 def book_tree(book_list, books_by_parent):
152     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
153         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
154         ) for book in book_list)
155
156     if text:
157         return "<ol>%s</ol>" % text
158     else:
159         return ''
160
161
162 @register.simple_tag
163 def user_creation_form():
164     return RegistrationForm(prefix='registration').as_ul()
165
166
167 @register.simple_tag
168 def authentication_form():
169     return LoginForm(prefix='login').as_ul()
170
171
172 @register.inclusion_tag('catalogue/breadcrumbs.html')
173 def breadcrumbs(tags, search_form=True):
174     from catalogue.forms import SearchForm
175     context = {'tag_list': tags}
176     try:
177         max_tag_list = settings.MAX_TAG_LIST
178     except AttributeError:
179         max_tag_list = -1
180     if search_form and (max_tag_list == -1 or len(tags) < max_tag_list):
181         context['search_form'] = SearchForm(tags=tags)
182     return context
183
184
185 @register.tag
186 def catalogue_url(parser, token):
187     bits = token.split_contents()
188     tag_name = bits[0]
189
190     tags_to_add = []
191     tags_to_remove = []
192     for bit in bits[1:]:
193         if bit[0] == '-':
194             tags_to_remove.append(bit[1:])
195         else:
196             tags_to_add.append(bit)
197
198     return CatalogueURLNode(tags_to_add, tags_to_remove)
199
200
201 class CatalogueURLNode(Node):
202     def __init__(self, tags_to_add, tags_to_remove):
203         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
204         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
205
206     def render(self, context):
207         tags_to_add = []
208         tags_to_remove = []
209
210         for tag_variable in self.tags_to_add:
211             tag = tag_variable.resolve(context)
212             if isinstance(tag, (list, dict)):
213                 tags_to_add += [t for t in tag]
214             else:
215                 tags_to_add.append(tag)
216
217         for tag_variable in self.tags_to_remove:
218             tag = tag_variable.resolve(context)
219             if iterable(tag):
220                 tags_to_remove += [t for t in tag]
221             else:
222                 tags_to_remove.append(tag)
223
224         tag_slugs = [tag.url_chunk for tag in tags_to_add]
225         for tag in tags_to_remove:
226             try:
227                 tag_slugs.remove(tag.url_chunk)
228             except KeyError:
229                 pass
230
231         if len(tag_slugs) > 0:
232             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
233         else:
234             return reverse('main_page')
235
236
237 @register.inclusion_tag('catalogue/latest_blog_posts.html')
238 def latest_blog_posts(feed_url, posts_to_show=5):
239     try:
240         feed = feedparser.parse(str(feed_url))
241         posts = []
242         for i in range(posts_to_show):
243             pub_date = feed['entries'][i].updated_parsed
244             published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
245             posts.append({
246                 'title': feed['entries'][i].title,
247                 'summary': feed['entries'][i].summary,
248                 'link': feed['entries'][i].link,
249                 'date': published,
250                 })
251         return {'posts': posts}
252     except:
253         return {'posts': []}
254
255
256 @register.inclusion_tag('catalogue/tag_list.html')
257 def tag_list(tags, choices=None):
258     if choices is None:
259         choices = []
260     if len(tags) == 1:
261         one_tag = tags[0]
262     return locals()
263
264
265 @register.inclusion_tag('catalogue/folded_tag_list.html')
266 def folded_tag_list(tags, choices=None):
267     tags = [tag for tag in tags if tag.count]
268     if choices is None:
269         choices = []
270     some_tags_hidden = False
271     tag_count = len(tags)
272
273     if tag_count == 1:
274         one_tag = tags[0]
275     else:
276         shown_tags = [tag for tag in tags if tag.main_page]
277         if tag_count > len(shown_tags):
278             some_tags_hidden = True
279     return locals()
280