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