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