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