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