61b384649170ea39f65a9fb13ac40907fbc2d422
[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 datetime
6 import feedparser
7
8 from django import template
9 from django.template import Node, Variable, Template, Context
10 from django.core.cache import cache
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.utils.translation import ugettext as _
14
15 from catalogue import forms
16 from catalogue.utils import split_tags
17 from catalogue.models import Book, Fragment, Tag
18
19 register = template.Library()
20
21
22 class RegistrationForm(UserCreationForm):
23     def as_ul(self):
24         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
25         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)
26
27
28 class LoginForm(AuthenticationForm):
29     def as_ul(self):
30         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
31         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)
32
33
34 def iterable(obj):
35     try:
36         iter(obj)
37         return True
38     except TypeError:
39         return False
40
41
42 def capfirst(text):
43     try:
44         return '%s%s' % (text[0].upper(), text[1:])
45     except IndexError:
46         return ''
47
48 @register.filter
49 def build_absolute_uri(uri, request):
50     return request.build_absolute_uri(uri)
51
52
53 @register.simple_tag
54 def html_title_from_tags(tags):
55     if len(tags) < 2:
56         return title_from_tags(tags)
57     template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
58     return capfirst(",<br/>".join(
59         template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
60     
61
62
63 def simple_title(tags):
64     title = []
65     for tag in tags:
66         title.append("%s: %s" % (_(tag.category), tag.name))
67     return capfirst(', '.join(title))
68
69
70 @register.simple_tag
71 def book_title(book, html_links=False):
72     return book.pretty_title(html_links)
73
74
75 @register.simple_tag
76 def book_title_html(book):
77     return book_title(book, html_links=True)
78
79
80 @register.simple_tag
81 def title_from_tags(tags):
82     def split_tags(tags):
83         result = {}
84         for tag in tags:
85             result[tag.category] = tag
86         return result
87
88     # TODO: Remove this after adding flection mechanism
89     return simple_title(tags)
90
91     class Flection(object):
92         def get_case(self, name, flection):
93             return name
94     flection = Flection()
95
96     self = split_tags(tags)
97
98     title = u''
99
100     # Specjalny przypadek oglądania wszystkich lektur na danej półce
101     if len(self) == 1 and 'set' in self:
102         return u'Półka %s' % self['set']
103
104     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
105     # jest wybrana przez użytkownika
106     if 'epoch' in self and len(self) == 1:
107         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
108         return capfirst(text)
109
110     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
111     # są tylko rodzaj literacki i autor
112     if 'kind' in self and 'author' in self and len(self) == 2:
113         text = u'%s w twórczości %s' % (unicode(self['kind']),
114             flection.get_case(unicode(self['author']), u'dopełniacz'))
115         return capfirst(text)
116
117     # Przypadki ogólniejsze
118     if 'theme' in self:
119         title += u'Motyw %s' % unicode(self['theme'])
120
121     if 'genre' in self:
122         if 'theme' in self:
123             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
124         else:
125             title += unicode(self['genre'])
126
127     if 'kind' in self or 'author' in self or 'epoch' in self:
128         if 'genre' in self or 'theme' in self:
129             if 'kind' in self:
130                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
131             else:
132                 title += u' w twórczości '
133         else:
134             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
135
136     if 'author' in self:
137         title += flection.get_case(unicode(self['author']), u'dopełniacz')
138     elif 'epoch' in self:
139         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
140
141     return capfirst(title)
142
143
144 @register.simple_tag
145 def book_tree(book_list, books_by_parent):
146     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
147         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
148         ) for book in book_list)
149
150     if text:
151         return "<ol>%s</ol>" % text
152     else:
153         return ''
154
155 @register.simple_tag
156 def audiobook_tree(book_list, books_by_parent):
157     text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
158         reverse("book_player", args=[book.slug]), book.title, audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
159         ) for book in book_list)
160
161     if text:
162         return "<ol>%s</ol>" % text
163     else:
164         return ''
165
166 @register.simple_tag
167 def book_tree_texml(book_list, books_by_parent, depth=1):
168     return "".join("""
169             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
170             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
171             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
172             <ctrl ch='\\' />
173             %(children)s
174             """ % {
175                 "depth": depth,
176                 "title": book.title, 
177                 "audiences": ", ".join(book.audiences_pl()),
178                 "audiobook": "audiobook" if book.has_media('mp3') else "",
179                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
180             } for book in book_list)
181
182
183 @register.simple_tag
184 def all_editors(extra_info):
185     editors = []
186     if 'editors' in extra_info:
187         editors += extra_info['editors']
188     if 'technical_editors' in extra_info:
189         editors += extra_info['technical_editors']
190     # support for extra_info-s from librarian<1.2
191     if 'editor' in extra_info:
192         editors.append(extra_info['editor'])
193     if 'technical_editor' in extra_info:
194         editors.append(extra_info['technical_editor'])
195     return ', '.join(
196                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
197                      for person in sorted(set(editors)))
198
199
200 @register.simple_tag
201 def user_creation_form():
202     return RegistrationForm(prefix='registration').as_ul()
203
204
205 @register.simple_tag
206 def authentication_form():
207     return LoginForm(prefix='login').as_ul()
208
209
210 @register.tag
211 def catalogue_url(parser, token):
212     bits = token.split_contents()
213     tag_name = bits[0]
214
215     tags_to_add = []
216     tags_to_remove = []
217     for bit in bits[1:]:
218         if bit[0] == '-':
219             tags_to_remove.append(bit[1:])
220         else:
221             tags_to_add.append(bit)
222
223     return CatalogueURLNode(tags_to_add, tags_to_remove)
224
225
226 class CatalogueURLNode(Node):
227     def __init__(self, tags_to_add, tags_to_remove):
228         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
229         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
230
231     def render(self, context):
232         tags_to_add = []
233         tags_to_remove = []
234
235         for tag_variable in self.tags_to_add:
236             tag = tag_variable.resolve(context)
237             if isinstance(tag, (list, dict)):
238                 tags_to_add += [t for t in tag]
239             else:
240                 tags_to_add.append(tag)
241
242         for tag_variable in self.tags_to_remove:
243             tag = tag_variable.resolve(context)
244             if iterable(tag):
245                 tags_to_remove += [t for t in tag]
246             else:
247                 tags_to_remove.append(tag)
248
249         tag_slugs = [tag.url_chunk for tag in tags_to_add]
250         for tag in tags_to_remove:
251             try:
252                 tag_slugs.remove(tag.url_chunk)
253             except KeyError:
254                 pass
255
256         if len(tag_slugs) > 0:
257             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
258         else:
259             return reverse('main_page')
260
261
262 @register.inclusion_tag('catalogue/latest_blog_posts.html')
263 def latest_blog_posts(feed_url, posts_to_show=5):
264     try:
265         feed = feedparser.parse(str(feed_url))
266         posts = []
267         for i in range(posts_to_show):
268             pub_date = feed['entries'][i].updated_parsed
269             published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
270             posts.append({
271                 'title': feed['entries'][i].title,
272                 'summary': feed['entries'][i].summary,
273                 'link': feed['entries'][i].link,
274                 'date': published,
275                 })
276         return {'posts': posts}
277     except:
278         return {'posts': []}
279
280
281 @register.inclusion_tag('catalogue/tag_list.html')
282 def tag_list(tags, choices=None):
283     if choices is None:
284         choices = []
285     if len(tags) == 1 and tags[0].category not in [t.category for t in choices]:
286         one_tag = tags[0]
287     return locals()
288
289
290 @register.inclusion_tag('catalogue/inline_tag_list.html')
291 def inline_tag_list(tags, choices=None):
292     return tag_list(tags, choices)
293
294
295 @register.inclusion_tag('catalogue/book_info.html')
296 def book_info(book):
297     return locals()
298
299
300 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
301 def book_wide(context, book):
302     theme_counter = book.theme_counter
303     book_themes = Tag.objects.filter(pk__in=theme_counter.keys())
304     for tag in book_themes:
305         tag.count = theme_counter[tag.pk]
306     extra_info = book.get_extra_info_value()
307     hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
308
309     return {
310         'book': book,
311         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
312         'related': book.related_info(),
313         'extra_info': book.get_extra_info_value(),
314         'hide_about': hide_about,
315         'themes': book_themes,
316         'custom_pdf_form': forms.CustomPDFForm(),
317         'request': context.get('request'),
318     }
319
320
321 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
322 def book_short(context, book):
323     return {
324         'book': book,
325         'main_link': book.get_absolute_url(),
326         'related': book.related_info(),
327         'request': context.get('request'),
328     }
329
330
331 @register.inclusion_tag('catalogue/book_mini_box.html')
332 def book_mini(book):
333     return {
334         'book': book,
335         'related': book.related_info(),
336     }
337
338
339 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
340 def work_list(context, object_list):
341     request = context.get('request')
342     if object_list:
343         object_type = type(object_list[0]).__name__
344     return locals()
345
346
347 @register.inclusion_tag('catalogue/fragment_promo.html')
348 def fragment_promo(arg=None):
349     if arg is None:
350         fragments = Fragment.objects.all().order_by('?')
351         fragment = fragments[0] if fragments.exists() else None
352     elif isinstance(arg, Book):
353         fragment = arg.choose_fragment()
354     else:
355         fragments = Fragment.tagged.with_all(arg).order_by('?')
356         fragment = fragments[0] if fragments.exists() else None
357
358     return {
359         'fragment': fragment,
360     }
361
362
363 @register.inclusion_tag('catalogue/related_books.html')
364 def related_books(book, limit=6, random=1):
365     cache_key = "catalogue.related_books.%d.%d" % (book.id, limit - random)
366     related = cache.get(cache_key)
367     if related is None:
368         related = list(Book.objects.filter(
369             common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
370         limit -= len(related)
371         if limit > random:
372             related += Book.tagged.related_to(book,
373                     Book.objects.exclude(common_slug=book.common_slug),
374                     ignore_by_tag=book.book_tag())[:limit-random]
375         cache.set(cache_key, related, 1800)
376     if random:
377         related += list(Book.objects.exclude(
378                         pk__in=[b.pk for b in related] + [book.pk]
379                     ).order_by('?')[:random])
380     return {
381         'books': related,
382     }
383
384
385 @register.inclusion_tag('catalogue/menu.html')
386 def catalogue_menu():
387     tags = Tag.objects.filter(
388             category__in=('author', 'epoch', 'genre', 'kind', 'theme')
389         ).exclude(book_count=0)
390     return split_tags(tags)
391     
392
393
394 @register.simple_tag
395 def tag_url(category, slug):
396     return reverse('catalogue.views.tagged_object_list', args=[
397         '/'.join((Tag.categories_dict[category], slug))
398     ])