newsletter checkboxes in suggestions and registration
[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.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 picture.models import Picture
22
23 register = template.Library()
24
25
26 def iterable(obj):
27     try:
28         iter(obj)
29         return True
30     except TypeError:
31         return False
32
33
34 def capfirst(text):
35     try:
36         return '%s%s' % (text[0].upper(), text[1:])
37     except IndexError:
38         return ''
39
40
41 @register.simple_tag
42 def html_title_from_tags(tags):
43     if len(tags) < 2:
44         return title_from_tags(tags)
45     template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
46     return capfirst(",<br/>".join(
47         template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
48
49
50 def simple_title(tags):
51     title = []
52     for tag in tags:
53         title.append("%s: %s" % (_(tag.category), tag.name))
54     return capfirst(', '.join(title))
55
56
57 @register.simple_tag
58 def book_title(book, html_links=False):
59     return book.pretty_title(html_links)
60
61
62 @register.simple_tag
63 def book_title_html(book):
64     return book_title(book, html_links=True)
65
66
67 @register.simple_tag
68 def title_from_tags(tags):
69     def split_tags(tags):
70         result = {}
71         for tag in tags:
72             result[tag.category] = tag
73         return result
74
75     # TODO: Remove this after adding flection mechanism
76     return simple_title(tags)
77
78     class Flection(object):
79         def get_case(self, name, flection):
80             return name
81     flection = Flection()
82
83     self = split_tags(tags)
84
85     title = u''
86
87     # Specjalny przypadek oglądania wszystkich lektur na danej półce
88     if len(self) == 1 and 'set' in self:
89         return u'Półka %s' % self['set']
90
91     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
92     # jest wybrana przez użytkownika
93     if 'epoch' in self and len(self) == 1:
94         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
95         return capfirst(text)
96
97     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
98     # są tylko rodzaj literacki i autor
99     if 'kind' in self and 'author' in self and len(self) == 2:
100         text = u'%s w twórczości %s' % (
101             unicode(self['kind']), flection.get_case(unicode(self['author']), u'dopełniacz'))
102         return capfirst(text)
103
104     # Przypadki ogólniejsze
105     if 'theme' in self:
106         title += u'Motyw %s' % unicode(self['theme'])
107
108     if 'genre' in self:
109         if 'theme' in self:
110             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
111         else:
112             title += unicode(self['genre'])
113
114     if 'kind' in self or 'author' in self or 'epoch' in self:
115         if 'genre' in self or 'theme' in self:
116             if 'kind' in self:
117                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
118             else:
119                 title += u' w twórczości '
120         else:
121             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
122
123     if 'author' in self:
124         title += flection.get_case(unicode(self['author']), u'dopełniacz')
125     elif 'epoch' in self:
126         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
127
128     return capfirst(title)
129
130
131 @register.simple_tag
132 def book_tree(book_list, books_by_parent):
133     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
134         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
135         ) for book in book_list)
136
137     if text:
138         return "<ol>%s</ol>" % text
139     else:
140         return ''
141
142
143 @register.simple_tag
144 def audiobook_tree(book_list, books_by_parent):
145     text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
146         reverse("book_player", args=[book.slug]), book.title,
147         audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
148     ) for book in book_list)
149
150     if text:
151         return "<ol>%s</ol>" % text
152     else:
153         return ''
154
155
156 @register.simple_tag
157 def book_tree_texml(book_list, books_by_parent, depth=1):
158     return "".join("""
159             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
160             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
161             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
162             <ctrl ch='\\' />
163             %(children)s
164             """ % {
165                 "depth": depth,
166                 "title": book.title,
167                 "audiences": ", ".join(book.audiences_pl()),
168                 "audiobook": "audiobook" if book.has_media('mp3') else "",
169                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
170             } for book in book_list)
171
172
173 @register.simple_tag
174 def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
175     def quote_if_necessary(s):
176         try:
177             s.index(delimeter)
178             s.replace('"', '\\"')
179             return '"%s"' % s
180         except ValueError:
181             return s
182
183     return "".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
184 %(children)s""" % {
185                 "d": delimeter,
186                 "preindent": delimeter * (depth - 1),
187                 "postindent": delimeter * (max_depth - depth),
188                 "depth": depth,
189                 "author": quote_if_necessary(author.name),
190                 "title": quote_if_necessary(book.title),
191                 "audiences": ", ".join(book.audiences_pl()),
192                 "audiobook": "audiobook" if book.has_media('mp3') else "",
193                 "children": book_tree_csv(author, books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
194             } for book in book_list)
195
196
197 @register.simple_tag
198 def all_editors(extra_info):
199     editors = []
200     if 'editors' in extra_info:
201         editors += extra_info['editors']
202     if 'technical_editors' in extra_info:
203         editors += extra_info['technical_editors']
204     # support for extra_info-s from librarian<1.2
205     if 'editor' in extra_info:
206         editors.append(extra_info['editor'])
207     if 'technical_editor' in extra_info:
208         editors.append(extra_info['technical_editor'])
209     return ', '.join(
210                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
211                      for person in sorted(set(editors)))
212
213
214 @register.tag
215 def catalogue_url(parser, token):
216     bits = token.split_contents()
217
218     tags_to_add = []
219     tags_to_remove = []
220     for bit in bits[2:]:
221         if bit[0] == '-':
222             tags_to_remove.append(bit[1:])
223         else:
224             tags_to_add.append(bit)
225
226     return CatalogueURLNode(bits[1], tags_to_add, tags_to_remove)
227
228
229 class CatalogueURLNode(Node):
230     def __init__(self, list_type, tags_to_add, tags_to_remove):
231         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
232         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
233         self.list_type_var = Variable(list_type)
234
235     def render(self, context):
236         list_type = self.list_type_var.resolve(context)
237         tags_to_add = []
238         tags_to_remove = []
239
240         for tag_variable in self.tags_to_add:
241             tag = tag_variable.resolve(context)
242             if isinstance(tag, (list, dict)):
243                 tags_to_add += [t for t in tag]
244             else:
245                 tags_to_add.append(tag)
246
247         for tag_variable in self.tags_to_remove:
248             tag = tag_variable.resolve(context)
249             if iterable(tag):
250                 tags_to_remove += [t for t in tag]
251             else:
252                 tags_to_remove.append(tag)
253
254         tag_slugs = [tag.url_chunk for tag in tags_to_add]
255         for tag in tags_to_remove:
256             try:
257                 tag_slugs.remove(tag.url_chunk)
258             except KeyError:
259                 pass
260
261         if len(tag_slugs) > 0:
262             if list_type == 'gallery':
263                 return reverse('tagged_object_list_gallery', kwargs={'tags': '/'.join(tag_slugs)})
264             elif list_type == 'audiobooks':
265                 return reverse('tagged_object_list_audiobooks', kwargs={'tags': '/'.join(tag_slugs)})
266             else:
267                 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
268         else:
269             if list_type == 'gallery':
270                 return reverse('gallery')
271             elif list_type == 'audiobooks':
272                 return reverse('audiobook_list')
273             else:
274                 return reverse('book_list')
275
276
277 # @register.inclusion_tag('catalogue/tag_list.html')
278 def tag_list(tags, choices=None, category=None, list_type='books'):
279     # print(tags, choices, category)
280     if choices is None:
281         choices = []
282
283     if category is None and tags:
284         category = tags[0].category
285
286     category_choices = [tag for tag in choices if tag.category == category]
287
288     if len(tags) == 1 and category not in [t.category for t in choices]:
289         one_tag = tags[0]
290     else:
291         one_tag = None
292
293     if category is not None:
294         other = Tag.objects.filter(category=category).exclude(pk__in=[t.pk for t in tags])\
295             .exclude(pk__in=[t.pk for t in category_choices])
296         # Filter out empty tags.
297         ct = ContentType.objects.get_for_model(Picture if list_type == 'gallery' else Book)
298         other = other.filter(items__content_type=ct).distinct()
299         if list_type == 'audiobooks':
300             other = other.filter(id__in=get_audiobook_tags())
301         other = other.only('name', 'slug', 'category')
302     else:
303         other = []
304
305     return {
306         'one_tag': one_tag,
307         'choices': choices,
308         'category_choices': category_choices,
309         'tags': tags,
310         'other': other,
311         'list_type': list_type,
312     }
313
314
315 @register.inclusion_tag('catalogue/inline_tag_list.html')
316 def inline_tag_list(tags, choices=None, category=None, list_type='books'):
317     return tag_list(tags, choices, category, list_type)
318
319
320 @register.inclusion_tag('catalogue/collection_list.html')
321 def collection_list(collections):
322     return {'collections': collections}
323
324
325 @register.inclusion_tag('catalogue/book_info.html')
326 def book_info(book):
327     return {
328         'is_picture': isinstance(book, Picture),
329         'book': book,
330     }
331
332
333 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
334 def work_list(context, object_list):
335     request = context.get('request')
336     return {'object_list': object_list, 'request': request}
337
338
339 @register.inclusion_tag('catalogue/plain_list.html', takes_context=True)
340 def plain_list(context, object_list, with_initials=True, by_author=False, choice=None, book=None, list_type='books',
341                paged=True, initial_blocks=False):
342     names = [('', [])]
343     last_initial = None
344     if len(object_list) < settings.CATALOGUE_MIN_INITIALS and not by_author:
345         with_initials = False
346         initial_blocks = False
347     for obj in object_list:
348         if with_initials:
349             if by_author:
350                 initial = obj.sort_key_author
351             else:
352                 initial = obj.get_initial().upper()
353             if initial != last_initial:
354                 last_initial = initial
355                 names.append((obj.author_unicode() if by_author else initial, []))
356         names[-1][1].append(obj)
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.all()
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):
405     links = []
406     if 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 "".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 @ssi_variable(register, patch_response=[add_never_cache_headers])
457 def catalogue_random_book(request, exclude_ids):
458     from .. import app_settings
459     if random() < app_settings.RELATED_RANDOM_PICTURE_CHANCE:
460         return None
461     queryset = Book.objects.exclude(pk__in=exclude_ids)
462     count = queryset.count()
463     if count:
464         return queryset[randint(0, count - 1)].pk
465     else:
466         return None
467
468
469 @ssi_variable(register, patch_response=[add_never_cache_headers])
470 def choose_fragment(request, book_id=None, tag_ids=None, unless=False):
471     if unless:
472         return None
473
474     if book_id is not None:
475         fragment = Book.objects.get(pk=book_id).choose_fragment()
476     else:
477         if tag_ids is not None:
478             tags = Tag.objects.filter(pk__in=tag_ids)
479             fragments = Fragment.tagged.with_all(tags).order_by().only('id')
480         else:
481             fragments = Fragment.objects.all().order_by().only('id')
482         fragment_count = fragments.count()
483         fragment = fragments[randint(0, fragment_count - 1)] if fragment_count else None
484     return fragment.pk if fragment is not None else None
485
486
487 @register.filter
488 def strip_tag(html, tag_name):
489     # docelowo może być warto zainstalować BeautifulSoup do takich rzeczy
490     import re
491     return re.sub(r"<.?%s\b[^>]*>" % tag_name, "", html)