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