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