1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from random import randint, random
5 from urllib.parse import urlparse
6 from django.contrib.contenttypes.models import ContentType
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 _
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
22 register = template.Library()
35 return '%s%s' % (text[0].upper(), text[1:])
41 def html_title_from_tags(tags):
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)))
49 def simple_title(tags):
52 title.append("%s: %s" % (_(tag.category), tag.name))
53 return capfirst(', '.join(title))
57 def book_title(book, html_links=False):
58 return mark_safe(book.pretty_title(html_links))
62 def book_title_html(book):
63 return book_title(book, html_links=True)
67 def title_from_tags(tags):
71 result[tag.category] = tag
74 # TODO: Remove this after adding flection mechanism
75 return simple_title(tags)
77 class Flection(object):
78 def get_case(self, name, flection):
82 self = split_tags(tags)
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']
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')
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)
103 # Przypadki ogólniejsze
105 title += 'Motyw %s' % str(self['theme'])
109 title += ' w %s' % flection.get_case(str(self['genre']), 'miejscownik')
111 title += str(self['genre'])
113 if 'kind' in self or 'author' in self or 'epoch' in self:
114 if 'genre' in self or 'theme' in self:
116 title += ' w %s ' % flection.get_case(str(self['kind']), 'miejscownik')
118 title += ' w twórczości '
120 title += '%s ' % str(self.get('kind', 'twórczość'))
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')
127 return capfirst(title)
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)
137 return mark_safe("<ol>%s</ol>" % text)
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)
150 return mark_safe("<ol>%s</ol>" % text)
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>
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))
173 def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
174 def quote_if_necessary(s):
177 s.replace('"', '\\"')
182 return mark_safe("".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
185 "preindent": delimeter * (depth - 1),
186 "postindent": delimeter * (max_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))
197 def all_editors(extra_info):
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'])
209 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
210 for person in sorted(set(editors)))
214 def catalogue_url(parser, token):
215 bits = token.split_contents()
221 tags_to_remove.append(bit[1:])
223 tags_to_add.append(bit)
225 return CatalogueURLNode(bits[1], tags_to_add, tags_to_remove)
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)
234 def render(self, context):
235 list_type = self.list_type_var.resolve(context)
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]
244 tags_to_add.append(tag)
246 for tag_variable in self.tags_to_remove:
247 tag = tag_variable.resolve(context)
249 tags_to_remove += [t for t in tag]
251 tags_to_remove.append(tag)
253 tag_slugs = [tag.url_chunk for tag in tags_to_add]
254 for tag in tags_to_remove:
256 tag_slugs.remove(tag.url_chunk)
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)})
266 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
268 if list_type == 'gallery':
269 return reverse('gallery')
270 elif list_type == 'audiobooks':
271 return reverse('audiobook_list')
273 return reverse('book_list')
276 # @register.inclusion_tag('catalogue/tag_list.html')
277 def tag_list(tags, choices=None, category=None, list_type='books'):
281 if category is None and tags:
282 category = tags[0].category
284 category_choices = [tag for tag in choices if tag.category == category]
286 if len(tags) == 1 and category not in [t.category for t in choices]:
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')
306 'category_choices': category_choices,
309 'list_type': list_type,
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)
318 @register.inclusion_tag('catalogue/collection_list.html')
319 def collection_list(collections):
320 return {'collections': collections}
323 @register.inclusion_tag('catalogue/book_info.html')
326 'is_picture': isinstance(book, Picture),
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}
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):
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:
348 initial = obj.sort_key_author
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] == ('', []):
360 'initial_blocks': initial_blocks,
362 'list_type': list_type,
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):
371 max_books = limit - random
372 is_picture = isinstance(instance, Picture)
374 pics_qs = Picture.objects.all()
376 pics_qs = pics_qs.exclude(pk=instance.pk)
377 pics = Picture.tagged.related_to(instance, pics_qs)
379 # Reserve one spot for an image.
382 books_qs = Book.objects.filter(findable=True)
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]
387 pics = pics[:1 + max_books - books.count()]
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)
394 'request': context['request'],
398 'random_excluded_books': random_excluded_books,
399 'random_excluded_pics': random_excluded_pics,
404 def download_audio(book, daisy=True, mp3=True):
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))
418 @register.inclusion_tag("catalogue/snippets/custom_pdf_link_li.html")
419 def custom_pdf_link_li(book):
422 'NO_CUSTOM_PDF': settings.NO_CUSTOM_PDF,
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)
433 "license_url": license_url,
434 "icon": "img/licenses/%s.png" % known['icon'],
435 "license_description": known['description'],
441 return obj.__class__.__name__
445 def source_name(url):
447 netloc = urlparse(url).netloc
449 netloc = urlparse('http://' + url).netloc
452 source, created = Source.objects.get_or_create(netloc=netloc)
453 return source.name or netloc
457 def catalogue_random_book(exclude_ids):
458 from .. import app_settings
459 if random() < app_settings.RELATED_RANDOM_PICTURE_CHANCE:
461 queryset = Book.objects.filter(findable=True).exclude(pk__in=exclude_ids)
462 count = queryset.count()
464 return queryset[randint(0, count - 1)]
470 def choose_fragment(book=None, tag_ids=None):
472 fragment = book.choose_fragment()
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')
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
485 def strip_tag(html, tag_name):
486 # docelowo może być warto zainstalować BeautifulSoup do takich rzeczy
488 return re.sub(r"<.?%s\b[^>]*>" % tag_name, "", html)
492 def status(book, user):
495 elif Membership.is_active_for(user):
501 @register.inclusion_tag('catalogue/snippets/content_warning.html')
502 def content_warning(book):
504 'wulgaryzmy': _('vulgar language'),
506 warnings = book.get_extra_info_json().get('content_warnings', [])
508 warnings_def.get(w, w)