718ffd358118364d6c92a0391f804488877a9ff9
[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 gettext 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     # TODO: Remove this after adding flection mechanism
69     return simple_title(tags)
70
71
72 @register.simple_tag
73 def nice_title_from_tags(tags, related_tags):
74     def split_tags(tags):
75         result = {}
76         for tag in tags:
77             result.setdefault(tag.category, []).append(tag)
78         return result
79
80     self = split_tags(tags)
81
82     pieces = []
83     plural = True
84     epoch_reduntant = False
85
86     if 'genre' in self:
87         pieces.append([
88             t.plural or t.name for t in self['genre']
89         ])
90         epoch_reduntant = self['genre'][-1].genre_epoch_specific
91     else:
92         # If we don't have genre,
93         # look if maybe we only have one genre in this context?
94         if 'genre' in related_tags and len(related_tags['genre']) == 1:
95             pieces.append([
96                 t.plural or t.name for t in related_tags['genre']
97             ])
98             epoch_reduntant = related_tags['genre'][-1].genre_epoch_specific
99         elif 'kind' in self:
100             # Only use kind if not talking about genre.
101             pieces.append([
102                 t.collective_noun or t.name for t in self['kind']
103             ])
104             plural = False
105         elif 'kind' in related_tags and len(related_tags['kind']) == 1:
106             # No info on genre, but there's only one kind related.
107             subpieces = []
108             pieces.append([
109                 t.collective_noun or t.name for t in self['kind']
110             ])
111             plural = False
112         else:
113             # We can't say anything about genre or kind.
114             pieces.append(['Twórczość'])
115             plural = False
116
117     if not epoch_reduntant and 'epoch' in self:
118         if plural:
119             form = lambda t: t.adjective_nonmasculine_plural or t.name
120         else:
121             form = lambda t: t.adjective_feminine_singular or t.name
122         pieces.append([
123             form(t) for t in self['epoch']
124         ])
125
126     if 'author' in self:
127         pieces.append([
128             t.genitive or t.name for t in self['author']
129         ])
130     
131     p = []
132     for sublist in pieces:
133         for item in sublist[:-2]:
134             p.append(item) + ','
135         for item in sublist[-2:-1]:
136             p.append(item) + ' i'
137         p.append(sublist[-1])
138
139     return ' '.join(p)
140
141
142 @register.simple_tag
143 def book_tree(book_list, books_by_parent):
144     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
145         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
146         ) for book in book_list)
147
148     if text:
149         return mark_safe("<ol>%s</ol>" % text)
150     else:
151         return ''
152
153
154 @register.simple_tag
155 def audiobook_tree(book_list, books_by_parent):
156     text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
157         reverse("book_player", args=[book.slug]), book.title,
158         audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
159     ) for book in book_list)
160
161     if text:
162         return mark_safe("<ol>%s</ol>" % text)
163     else:
164         return ''
165
166
167 @register.simple_tag
168 def book_tree_texml(book_list, books_by_parent, depth=1):
169     return mark_safe("".join("""
170             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
171             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
172             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
173             <ctrl ch='\\' />
174             %(children)s
175             """ % {
176                 "depth": depth,
177                 "title": book.title,
178                 "audiences": ", ".join(book.audiences_pl()),
179                 "audiobook": "audiobook" if book.has_media('mp3') else "",
180                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
181             } for book in book_list))
182
183
184 @register.simple_tag
185 def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
186     def quote_if_necessary(s):
187         try:
188             s.index(delimeter)
189             s.replace('"', '\\"')
190             return '"%s"' % s
191         except ValueError:
192             return s
193
194     return mark_safe("".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
195 %(children)s""" % {
196                 "d": delimeter,
197                 "preindent": delimeter * (depth - 1),
198                 "postindent": delimeter * (max_depth - depth),
199                 "depth": depth,
200                 "author": quote_if_necessary(author.name),
201                 "title": quote_if_necessary(book.title),
202                 "audiences": ", ".join(book.audiences_pl()),
203                 "audiobook": "audiobook" if book.has_media('mp3') else "",
204                 "children": book_tree_csv(author, books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
205             } for book in book_list))
206
207
208 @register.simple_tag
209 def all_editors(extra_info):
210     editors = []
211     if 'editors' in extra_info:
212         editors += extra_info['editors']
213     if 'technical_editors' in extra_info:
214         editors += extra_info['technical_editors']
215     # support for extra_info-s from librarian<1.2
216     if 'editor' in extra_info:
217         editors.append(extra_info['editor'])
218     if 'technical_editor' in extra_info:
219         editors.append(extra_info['technical_editor'])
220     return ', '.join(
221                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
222                      for person in sorted(set(editors)))
223
224
225 @register.tag
226 def catalogue_url(parser, token):
227     bits = token.split_contents()
228
229     tags_to_add = []
230     tags_to_remove = []
231     for bit in bits[2:]:
232         if bit[0] == '-':
233             tags_to_remove.append(bit[1:])
234         else:
235             tags_to_add.append(bit)
236
237     return CatalogueURLNode(bits[1], tags_to_add, tags_to_remove)
238
239
240 class CatalogueURLNode(Node):
241     def __init__(self, list_type, tags_to_add, tags_to_remove):
242         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
243         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
244         self.list_type_var = Variable(list_type)
245
246     def render(self, context):
247         list_type = self.list_type_var.resolve(context)
248         tags_to_add = []
249         tags_to_remove = []
250
251         for tag_variable in self.tags_to_add:
252             tag = tag_variable.resolve(context)
253             if isinstance(tag, (list, dict)):
254                 tags_to_add += [t for t in tag]
255             else:
256                 tags_to_add.append(tag)
257
258         for tag_variable in self.tags_to_remove:
259             tag = tag_variable.resolve(context)
260             if iterable(tag):
261                 tags_to_remove += [t for t in tag]
262             else:
263                 tags_to_remove.append(tag)
264
265         tag_slugs = [tag.url_chunk for tag in tags_to_add]
266         for tag in tags_to_remove:
267             try:
268                 tag_slugs.remove(tag.url_chunk)
269             except KeyError:
270                 pass
271
272         if len(tag_slugs) > 0:
273             if list_type == 'gallery':
274                 return reverse('tagged_object_list_gallery', kwargs={'tags': '/'.join(tag_slugs)})
275             elif list_type == 'audiobooks':
276                 return reverse('tagged_object_list_audiobooks', kwargs={'tags': '/'.join(tag_slugs)})
277             else:
278                 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
279         else:
280             if list_type == 'gallery':
281                 return reverse('gallery')
282             elif list_type == 'audiobooks':
283                 return reverse('audiobook_list')
284             else:
285                 return reverse('book_list')
286
287
288 # @register.inclusion_tag('catalogue/tag_list.html')
289 def tag_list(tags, choices=None, category=None, list_type='books'):
290     if choices is None:
291         choices = []
292
293     if category is None and tags:
294         category = tags[0].category
295
296     category_choices = [tag for tag in choices if tag.category == category]
297
298     if len(tags) == 1 and category not in [t.category for t in choices]:
299         one_tag = tags[0]
300     else:
301         one_tag = None
302
303     if category is not None:
304         other = Tag.objects.filter(category=category).exclude(pk__in=[t.pk for t in tags])\
305             .exclude(pk__in=[t.pk for t in category_choices])
306         # Filter out empty tags.
307         ct = ContentType.objects.get_for_model(Picture if list_type == 'gallery' else Book)
308         other = other.filter(items__content_type=ct).distinct()
309         if list_type == 'audiobooks':
310             other = other.filter(id__in=get_audiobook_tags())
311         other = other.only('name', 'slug', 'category')
312     else:
313         other = []
314
315     return {
316         'one_tag': one_tag,
317         'choices': choices,
318         'category_choices': category_choices,
319         'tags': tags,
320         'other': other,
321         'list_type': list_type,
322     }
323
324
325 @register.inclusion_tag('catalogue/inline_tag_list.html')
326 def inline_tag_list(tags, choices=None, category=None, list_type='books'):
327     return tag_list(tags, choices, category, list_type)
328
329
330 @register.inclusion_tag('catalogue/collection_list.html')
331 def collection_list(collections):
332     return {'collections': collections}
333
334
335 @register.inclusion_tag('catalogue/book_info.html')
336 def book_info(book):
337     return {
338         'is_picture': isinstance(book, Picture),
339         'book': book,
340     }
341
342
343 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
344 def work_list(context, object_list):
345     request = context.get('request')
346     return {'object_list': object_list, 'request': request}
347
348
349 @register.inclusion_tag('catalogue/plain_list.html', takes_context=True)
350 def plain_list(context, object_list, with_initials=True, by_author=False, choice=None, book=None, list_type='books',
351                paged=True, initial_blocks=False):
352     names = [('', [])]
353     last_initial = None
354     if len(object_list) < settings.CATALOGUE_MIN_INITIALS and not by_author:
355         with_initials = False
356         initial_blocks = False
357     for obj in object_list:
358         if with_initials:
359             if by_author:
360                 initial = obj.sort_key_author
361             else:
362                 initial = obj.get_initial().upper()
363             if initial != last_initial:
364                 last_initial = initial
365                 names.append((obj.author_unicode() if by_author else initial, []))
366         names[-1][1].append(obj)
367     if names[0] == ('', []):
368         del names[0]
369     return {
370         'paged': paged,
371         'names': names,
372         'initial_blocks': initial_blocks,
373         'book': book,
374         'list_type': list_type,
375         'choice': choice,
376     }
377
378
379 # TODO: These are no longer just books.
380 @register.inclusion_tag('catalogue/related_books.html', takes_context=True)
381 def related_books(context, instance, limit=6, random=1, taken=0):
382     limit -= taken
383     max_books = limit - random
384     is_picture = isinstance(instance, Picture)
385
386     pics_qs = Picture.objects.all()
387     if is_picture:
388         pics_qs = pics_qs.exclude(pk=instance.pk)
389     pics = Picture.tagged.related_to(instance, pics_qs)
390     if pics.exists():
391         # Reserve one spot for an image.
392         max_books -= 1
393
394     books_qs = Book.objects.filter(findable=True)
395     if not is_picture:
396         books_qs = books_qs.exclude(common_slug=instance.common_slug).exclude(ancestor=instance)
397     books = Book.tagged.related_to(instance, books_qs)[:max_books]
398
399     pics = pics[:1 + max_books - books.count()]
400
401     random_excluded_books = [b.pk for b in books]
402     random_excluded_pics = [p.pk for p in pics]
403     (random_excluded_pics if is_picture else random_excluded_books).append(instance.pk)
404
405     return {
406         'request': context['request'],
407         'books': books,
408         'pics': pics,
409         'random': random,
410         'random_excluded_books': random_excluded_books,
411         'random_excluded_pics': random_excluded_pics,
412     }
413
414
415 @register.simple_tag
416 def related_books_2022(instance, limit=4, taken=0):
417     limit -= taken
418     max_books = limit
419
420     books_qs = Book.objects.filter(findable=True)
421     books_qs = books_qs.exclude(common_slug=instance.common_slug).exclude(ancestor=instance)
422     books = Book.tagged.related_to(instance, books_qs)[:max_books]
423
424     return books
425     
426
427 @register.simple_tag
428 def download_audio(book, daisy=True, mp3=True):
429     links = []
430     if mp3 and book.has_media('mp3'):
431         links.append("<a href='%s'>%s</a>" % (
432             reverse('download_zip_mp3', args=[book.slug]), BookMedia.formats['mp3'].name))
433     if book.has_media('ogg'):
434         links.append("<a href='%s'>%s</a>" % (
435             reverse('download_zip_ogg', args=[book.slug]), BookMedia.formats['ogg'].name))
436     if daisy and book.has_media('daisy'):
437         for dsy in book.get_media('daisy'):
438             links.append("<a href='%s'>%s</a>" % (dsy.file.url, BookMedia.formats['daisy'].name))
439     if daisy and book.has_media('audio.epub'):
440         for dsy in book.get_media('audio.epub'):
441             links.append("<a href='%s'>%s</a>" % (dsy.file.url, BookMedia.formats['audio.epub'].name))
442     return mark_safe("".join(links))
443
444
445 @register.inclusion_tag("catalogue/snippets/custom_pdf_link_li.html")
446 def custom_pdf_link_li(book):
447     return {
448         'book': book,
449         'NO_CUSTOM_PDF': settings.NO_CUSTOM_PDF,
450     }
451
452
453 @register.inclusion_tag("catalogue/snippets/license_icon.html")
454 def license_icon(license_url):
455     """Creates a license icon, if the license_url is known."""
456     known = LICENSES.get(license_url)
457     if known is None:
458         return {}
459     return {
460         "license_url": license_url,
461         "icon": "img/licenses/%s.png" % known['icon'],
462         "license_description": known['description'],
463     }
464
465
466 @register.simple_tag
467 def license_locative(license_url, default):
468     return LICENSES.get(license_url, {}).get('locative', default)
469
470
471 @register.filter
472 def class_name(obj):
473     return obj.__class__.__name__
474
475
476 @register.simple_tag
477 def source_name(url):
478     url = url.lstrip()
479     netloc = urlparse(url).netloc
480     if not netloc:
481         netloc = urlparse('http://' + url).netloc
482     if not netloc:
483         return ''
484     source, created = Source.objects.get_or_create(netloc=netloc)
485     return source.name or netloc
486
487
488 @register.simple_tag
489 def catalogue_random_book(exclude_ids):
490     from .. import app_settings
491     if random() < app_settings.RELATED_RANDOM_PICTURE_CHANCE:
492         return None
493     queryset = Book.objects.filter(findable=True).exclude(pk__in=exclude_ids)
494     count = queryset.count()
495     if count:
496         return queryset[randint(0, count - 1)]
497     else:
498         return None
499
500
501 @register.simple_tag
502 def choose_fragment(book=None, tag_ids=None):
503     if book is not None:
504         fragment = book.choose_fragment()
505     else:
506         if tag_ids is not None:
507             tags = Tag.objects.filter(pk__in=tag_ids)
508             fragments = Fragment.tagged.with_all(tags).filter(book__findable=True).order_by().only('id')
509         else:
510             fragments = Fragment.objects.filter(book__findable=True).order_by().only('id')
511         fragment_count = fragments.count()
512         fragment = fragments[randint(0, fragment_count - 1)] if fragment_count else None
513     return fragment
514
515
516 @register.filter
517 def strip_tag(html, tag_name):
518     # docelowo może być warto zainstalować BeautifulSoup do takich rzeczy
519     import re
520     return re.sub(r"<.?%s\b[^>]*>" % tag_name, "", html)
521
522
523 @register.filter
524 def status(book, user):
525     if not book.preview:
526         return 'open'
527     elif book.is_accessible_to(user):
528         return 'preview'
529     else:
530         return 'closed'
531
532
533 @register.inclusion_tag('catalogue/snippets/content_warning.html')
534 def content_warning(book):
535     warnings_def = {
536         'wulgaryzmy': _('vulgar language'),
537     }
538     warnings = book.get_extra_info_json().get('content_warnings', [])
539     warnings = sorted(
540         warnings_def.get(w, w)
541         for w in warnings
542     )
543     return {
544         "warnings": warnings
545     }
546
547
548 @register.inclusion_tag('catalogue/preview_ad.html', takes_context=True)
549 def preview_ad(context):
550     book = Book.objects.filter(parent=None, preview=True).first()
551     return {
552         'accessible': book.is_accessible_to(context['request'].user),
553         'book': book,
554     }
555
556 @register.inclusion_tag('catalogue/preview_ad_homepage.html', takes_context=True)
557 def preview_ad_homepage(context):
558     book = Book.objects.filter(parent=None, preview=True).first()
559     return {
560         'accessible': book.is_accessible_to(context['request'].user),
561         'book': book,
562     }