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