Code layout change.
[wolnelektury.git] / src / 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 from random import randint, random
6 from urlparse import urlparse
7
8 from django.conf import settings
9 from django import template
10 from django.template import Node, Variable, Template, Context
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.utils.cache import add_never_cache_headers
14 from django.utils.translation import ugettext as _
15
16 from ssify import ssi_variable
17 from catalogue.models import Book, BookMedia, Fragment, Tag, Source
18 from catalogue.constants import LICENSES
19 from picture.models import Picture
20
21 register = template.Library()
22
23
24 class RegistrationForm(UserCreationForm):
25     def as_ul(self):
26         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
27         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)
28
29
30 class LoginForm(AuthenticationForm):
31     def as_ul(self):
32         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
33         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)
34
35
36 def iterable(obj):
37     try:
38         iter(obj)
39         return True
40     except TypeError:
41         return False
42
43
44 def capfirst(text):
45     try:
46         return '%s%s' % (text[0].upper(), text[1:])
47     except IndexError:
48         return ''
49
50
51 @register.simple_tag
52 def html_title_from_tags(tags):
53     if len(tags) < 2:
54         return title_from_tags(tags)
55     template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
56     return capfirst(",<br/>".join(
57         template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
58
59
60 def simple_title(tags):
61     title = []
62     for tag in tags:
63         title.append("%s: %s" % (_(tag.category), tag.name))
64     return capfirst(', '.join(title))
65
66
67 @register.simple_tag
68 def book_title(book, html_links=False):
69     return book.pretty_title(html_links)
70
71
72 @register.simple_tag
73 def book_title_html(book):
74     return book_title(book, html_links=True)
75
76
77 @register.simple_tag
78 def title_from_tags(tags):
79     def split_tags(tags):
80         result = {}
81         for tag in tags:
82             result[tag.category] = tag
83         return result
84
85     # TODO: Remove this after adding flection mechanism
86     return simple_title(tags)
87
88     class Flection(object):
89         def get_case(self, name, flection):
90             return name
91     flection = Flection()
92
93     self = split_tags(tags)
94
95     title = u''
96
97     # Specjalny przypadek oglądania wszystkich lektur na danej półce
98     if len(self) == 1 and 'set' in self:
99         return u'Półka %s' % self['set']
100
101     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
102     # jest wybrana przez użytkownika
103     if 'epoch' in self and len(self) == 1:
104         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
105         return capfirst(text)
106
107     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
108     # są tylko rodzaj literacki i autor
109     if 'kind' in self and 'author' in self and len(self) == 2:
110         text = u'%s w twórczości %s' % (unicode(self['kind']),
111             flection.get_case(unicode(self['author']), u'dopełniacz'))
112         return capfirst(text)
113
114     # Przypadki ogólniejsze
115     if 'theme' in self:
116         title += u'Motyw %s' % unicode(self['theme'])
117
118     if 'genre' in self:
119         if 'theme' in self:
120             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
121         else:
122             title += unicode(self['genre'])
123
124     if 'kind' in self or 'author' in self or 'epoch' in self:
125         if 'genre' in self or 'theme' in self:
126             if 'kind' in self:
127                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
128             else:
129                 title += u' w twórczości '
130         else:
131             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
132
133     if 'author' in self:
134         title += flection.get_case(unicode(self['author']), u'dopełniacz')
135     elif 'epoch' in self:
136         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
137
138     return capfirst(title)
139
140
141 @register.simple_tag
142 def book_tree(book_list, books_by_parent):
143     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
144         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
145         ) for book in book_list)
146
147     if text:
148         return "<ol>%s</ol>" % text
149     else:
150         return ''
151
152 @register.simple_tag
153 def audiobook_tree(book_list, books_by_parent):
154     text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
155         reverse("book_player", args=[book.slug]), book.title, audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
156         ) for book in book_list)
157
158     if text:
159         return "<ol>%s</ol>" % text
160     else:
161         return ''
162
163 @register.simple_tag
164 def book_tree_texml(book_list, books_by_parent, depth=1):
165     return "".join("""
166             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
167             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
168             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
169             <ctrl ch='\\' />
170             %(children)s
171             """ % {
172                 "depth": depth,
173                 "title": book.title,
174                 "audiences": ", ".join(book.audiences_pl()),
175                 "audiobook": "audiobook" if book.has_media('mp3') else "",
176                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
177             } for book in book_list)
178
179
180 @register.simple_tag
181 def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
182     def quote_if_necessary(s):
183         try:
184             s.index(delimeter)
185             s.replace('"', '\\"')
186             return '"%s"' % s
187         except ValueError:
188             return s
189
190     return "".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
191 %(children)s""" % {
192                 "d": delimeter,
193                 "preindent": delimeter * (depth - 1),
194                 "postindent": delimeter * (max_depth - depth),
195                 "depth": depth,
196                 "author": quote_if_necessary(author.name),
197                 "title": quote_if_necessary(book.title),
198                 "audiences": ", ".join(book.audiences_pl()),
199                 "audiobook": "audiobook" if book.has_media('mp3') else "",
200                 "children": book_tree_csv(author, books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
201             } for book in book_list)
202
203 @register.simple_tag
204 def all_editors(extra_info):
205     editors = []
206     if 'editors' in extra_info:
207         editors += extra_info['editors']
208     if 'technical_editors' in extra_info:
209         editors += extra_info['technical_editors']
210     # support for extra_info-s from librarian<1.2
211     if 'editor' in extra_info:
212         editors.append(extra_info['editor'])
213     if 'technical_editor' in extra_info:
214         editors.append(extra_info['technical_editor'])
215     return ', '.join(
216                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
217                      for person in sorted(set(editors)))
218
219
220 @register.simple_tag
221 def user_creation_form():
222     return RegistrationForm(prefix='registration').as_ul()
223
224
225 @register.simple_tag
226 def authentication_form():
227     return LoginForm(prefix='login').as_ul()
228
229
230 @register.tag
231 def catalogue_url(parser, token):
232     bits = token.split_contents()
233
234     tags_to_add = []
235     tags_to_remove = []
236     for bit in bits[1:]:
237         if bit[0] == '-':
238             tags_to_remove.append(bit[1:])
239         else:
240             tags_to_add.append(bit)
241
242     return CatalogueURLNode(tags_to_add, tags_to_remove)
243
244
245 class CatalogueURLNode(Node):
246     def __init__(self, tags_to_add, tags_to_remove):
247         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
248         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
249
250     def render(self, context):
251         tags_to_add = []
252         tags_to_remove = []
253
254         for tag_variable in self.tags_to_add:
255             tag = tag_variable.resolve(context)
256             if isinstance(tag, (list, dict)):
257                 tags_to_add += [t for t in tag]
258             else:
259                 tags_to_add.append(tag)
260
261         for tag_variable in self.tags_to_remove:
262             tag = tag_variable.resolve(context)
263             if iterable(tag):
264                 tags_to_remove += [t for t in tag]
265             else:
266                 tags_to_remove.append(tag)
267
268         tag_slugs = [tag.url_chunk for tag in tags_to_add]
269         for tag in tags_to_remove:
270             try:
271                 tag_slugs.remove(tag.url_chunk)
272             except KeyError:
273                 pass
274
275         if len(tag_slugs) > 0:
276             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
277         else:
278             return reverse('main_page')
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/collection_list.html')
296 def collection_list(collections):
297     return locals()
298
299
300 @register.inclusion_tag('catalogue/book_info.html')
301 def book_info(book):
302     return {
303         'is_picture': isinstance(book, Picture),
304         'book': book,
305     }
306
307
308 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
309 def work_list(context, object_list):
310     request = context.get('request')
311     return locals()
312
313
314 # TODO: These are no longer just books.
315 @register.inclusion_tag('catalogue/related_books.html', takes_context=True)
316 def related_books(context, instance, limit=6, random=1, taken=0):
317     limit = limit - taken
318     max_books = limit - random
319     is_picture = isinstance(instance, Picture)
320
321     pics_qs = Picture.objects.all()
322     if is_picture:
323         pics_qs = pics_qs.exclude(pk=instance.pk)
324     pics = Picture.tagged.related_to(instance, pics_qs)
325     if pics.exists():
326         # Reserve one spot for an image.
327         max_books -= 1
328
329     books_qs = Book.objects.all()
330     if not is_picture:
331         books_qs = books_qs.exclude(common_slug=instance.common_slug).exclude(ancestor=instance)
332     books = Book.tagged.related_to(instance, books_qs)[:max_books]
333
334     pics = pics[:1 + max_books - books.count()]
335
336     random_excluded_books = [b.pk for b in books]
337     random_excluded_pics = [p.pk for p in pics]
338     (random_excluded_pics if is_picture else random_excluded_books).append(instance.pk)
339
340     return {
341         'request': context['request'],
342         'books': books,
343         'pics': pics,
344         'random': random,
345         'random_excluded_books': random_excluded_books,
346         'random_excluded_pics': random_excluded_pics,
347     }
348
349
350 @register.inclusion_tag('catalogue/menu.html')
351 def catalogue_menu():
352     return {'categories': [
353                 ('author', _('Authors'), 'autorzy'),
354                 ('genre', _('Genres'), 'gatunki'),
355                 ('kind', _('Kinds'), 'rodzaje'),
356                 ('epoch', _('Epochs'), 'epoki'),
357                 ('theme', _('Themes'), 'motywy'),
358         ]}
359
360
361 @register.simple_tag
362 def download_audio(book, daisy=True):
363     links = []
364     if book.has_media('mp3'):
365         links.append("<a href='%s'>%s</a>" %
366             (reverse('download_zip_mp3', args=[book.slug]),
367                 BookMedia.formats['mp3'].name))
368     if book.has_media('ogg'):
369         links.append("<a href='%s'>%s</a>" %
370             (reverse('download_zip_ogg', args=[book.slug]),
371                 BookMedia.formats['ogg'].name))
372     if daisy and book.has_media('daisy'):
373         for dsy in book.get_media('daisy'):
374             links.append("<a href='%s'>%s</a>" %
375                 (dsy.file.url, BookMedia.formats['daisy'].name))
376     return ", ".join(links)
377
378
379 @register.inclusion_tag("catalogue/snippets/custom_pdf_link_li.html")
380 def custom_pdf_link_li(book):
381     return {
382         'book': book,
383         'NO_CUSTOM_PDF': settings.NO_CUSTOM_PDF,
384     }
385
386
387 @register.inclusion_tag("catalogue/snippets/license_icon.html")
388 def license_icon(license_url):
389     """Creates a license icon, if the license_url is known."""
390     known = LICENSES.get(license_url)
391     if known is None:
392         return {}
393     return {
394         "license_url": license_url,
395         "icon": "img/licenses/%s.png" % known['icon'],
396         "license_description": known['description'],
397     }
398
399
400 @register.filter
401 def class_name(obj):
402     return obj.__class__.__name__
403
404
405 @register.simple_tag
406 def source_name(url):
407     url = url.lstrip()
408     netloc = urlparse(url).netloc
409     if not netloc:
410         netloc = urlparse('http://' + url).netloc
411     if not netloc:
412         return ''
413     source, created = Source.objects.get_or_create(netloc=netloc)
414     return source.name or netloc
415
416
417 @ssi_variable(register, patch_response=[add_never_cache_headers])
418 def catalogue_random_book(request, exclude_ids):
419     from .. import app_settings
420     if random() < app_settings.RELATED_RANDOM_PICTURE_CHANCE:
421         return None
422     queryset = Book.objects.exclude(pk__in=exclude_ids)
423     count = queryset.count()
424     if count:
425         return queryset[randint(0, count - 1)].pk
426     else:
427         return None
428
429
430 @ssi_variable(register, patch_response=[add_never_cache_headers])
431 def choose_fragment(request, book_id=None, tag_ids=None, unless=False):
432     if unless:
433         return None
434
435     if book_id is not None:
436         fragment = Book.objects.get(pk=book_id).choose_fragment()
437     else:
438         if tag_ids is not None:
439             tags = Tag.objects.filter(pk__in=tag_ids)
440             fragments = Fragment.tagged.with_all(tags).order_by().only('id')
441         else:
442             fragments = Fragment.objects.all().order_by().only('id')
443         fragment_count = fragments.count()
444         fragment = fragments[randint(0, fragment_count - 1)] if fragment_count else None
445     return fragment.pk if fragment is not None else None