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 ssify import ssi_variable
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
24 register = template.Library()
37 return '%s%s' % (text[0].upper(), text[1:])
43 def html_title_from_tags(tags):
45 return title_from_tags(tags)
46 template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
47 return mark_safe(capfirst(",<br/>".join(
48 template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags)))
51 def simple_title(tags):
54 title.append("%s: %s" % (_(tag.category), tag.name))
55 return capfirst(', '.join(title))
59 def book_title(book, html_links=False):
60 return mark_safe(book.pretty_title(html_links))
64 def book_title_html(book):
65 return book_title(book, html_links=True)
69 def title_from_tags(tags):
73 result[tag.category] = tag
76 # TODO: Remove this after adding flection mechanism
77 return simple_title(tags)
79 class Flection(object):
80 def get_case(self, name, flection):
84 self = split_tags(tags)
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']
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')
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)
105 # Przypadki ogólniejsze
107 title += u'Motyw %s' % str(self['theme'])
111 title += u' w %s' % flection.get_case(str(self['genre']), u'miejscownik')
113 title += str(self['genre'])
115 if 'kind' in self or 'author' in self or 'epoch' in self:
116 if 'genre' in self or 'theme' in self:
118 title += u' w %s ' % flection.get_case(str(self['kind']), u'miejscownik')
120 title += u' w twórczości '
122 title += u'%s ' % str(self.get('kind', u'twórczość'))
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')
129 return capfirst(title)
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)
139 return mark_safe("<ol>%s</ol>" % text)
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)
152 return mark_safe("<ol>%s</ol>" % text)
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>
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))
175 def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
176 def quote_if_necessary(s):
179 s.replace('"', '\\"')
184 return mark_safe("".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
187 "preindent": delimeter * (depth - 1),
188 "postindent": delimeter * (max_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))
199 def all_editors(extra_info):
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'])
211 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
212 for person in sorted(set(editors)))
216 def catalogue_url(parser, token):
217 bits = token.split_contents()
223 tags_to_remove.append(bit[1:])
225 tags_to_add.append(bit)
227 return CatalogueURLNode(bits[1], tags_to_add, tags_to_remove)
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)
236 def render(self, context):
237 list_type = self.list_type_var.resolve(context)
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]
246 tags_to_add.append(tag)
248 for tag_variable in self.tags_to_remove:
249 tag = tag_variable.resolve(context)
251 tags_to_remove += [t for t in tag]
253 tags_to_remove.append(tag)
255 tag_slugs = [tag.url_chunk for tag in tags_to_add]
256 for tag in tags_to_remove:
258 tag_slugs.remove(tag.url_chunk)
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)})
268 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
270 if list_type == 'gallery':
271 return reverse('gallery')
272 elif list_type == 'audiobooks':
273 return reverse('audiobook_list')
275 return reverse('book_list')
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)
284 if category is None and tags:
285 category = tags[0].category
287 category_choices = [tag for tag in choices if tag.category == category]
289 if len(tags) == 1 and category not in [t.category for t in choices]:
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')
309 'category_choices': category_choices,
312 'list_type': list_type,
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)
321 @register.inclusion_tag('catalogue/collection_list.html')
322 def collection_list(collections):
323 return {'collections': collections}
326 @register.inclusion_tag('catalogue/book_info.html')
329 'is_picture': isinstance(book, Picture),
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}
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):
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:
351 initial = obj.sort_key_author
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] == ('', []):
363 'initial_blocks': initial_blocks,
365 'list_type': list_type,
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):
374 max_books = limit - random
375 is_picture = isinstance(instance, Picture)
377 pics_qs = Picture.objects.all()
379 pics_qs = pics_qs.exclude(pk=instance.pk)
380 pics = Picture.tagged.related_to(instance, pics_qs)
382 # Reserve one spot for an image.
385 books_qs = Book.objects.all()
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]
390 pics = pics[:1 + max_books - books.count()]
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)
397 'request': context['request'],
401 'random_excluded_books': random_excluded_books,
402 'random_excluded_pics': random_excluded_pics,
407 def download_audio(book, daisy=True, mp3=True):
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))
421 @register.inclusion_tag("catalogue/snippets/custom_pdf_link_li.html")
422 def custom_pdf_link_li(book):
425 'NO_CUSTOM_PDF': settings.NO_CUSTOM_PDF,
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)
436 "license_url": license_url,
437 "icon": "img/licenses/%s.png" % known['icon'],
438 "license_description": known['description'],
444 return obj.__class__.__name__
448 def source_name(url):
450 netloc = urlparse(url).netloc
452 netloc = urlparse('http://' + url).netloc
455 source, created = Source.objects.get_or_create(netloc=netloc)
456 return source.name or netloc
460 def catalogue_random_book(exclude_ids):
461 from .. import app_settings
462 if random() < app_settings.RELATED_RANDOM_PICTURE_CHANCE:
463 print('yay, picture')
465 queryset = Book.objects.exclude(pk__in=exclude_ids)
466 count = queryset.count()
468 return queryset[randint(0, count - 1)]
473 @ssi_variable(register, patch_response=[add_never_cache_headers])
474 def choose_fragment(request, book_id=None, tag_ids=None, unless=False):
478 if book_id is not None:
479 fragment = Book.objects.get(pk=book_id).choose_fragment()
481 if tag_ids is not None:
482 tags = Tag.objects.filter(pk__in=tag_ids)
483 fragments = Fragment.tagged.with_all(tags).order_by().only('id')
485 fragments = Fragment.objects.all().order_by().only('id')
486 fragment_count = fragments.count()
487 fragment = fragments[randint(0, fragment_count - 1)] if fragment_count else None
488 return fragment.pk if fragment is not None else None
492 def strip_tag(html, tag_name):
493 # docelowo może być warto zainstalować BeautifulSoup do takich rzeczy
495 return re.sub(r"<.?%s\b[^>]*>" % tag_name, "", html)
499 def status(book, user):
502 elif Membership.is_active_for(user):