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.
 
   5 from collections import OrderedDict
 
   9 from django.conf import settings
 
  10 from django.template import RequestContext
 
  11 from django.template.loader import render_to_string
 
  12 from django.shortcuts import render_to_response, get_object_or_404, render, redirect
 
  13 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
 
  14 from django.core.urlresolvers import reverse
 
  15 from django.db.models import Q
 
  16 from django.contrib.auth.decorators import login_required, user_passes_test
 
  17 from django.utils.http import urlquote_plus
 
  18 from django.utils import translation
 
  19 from django.utils.translation import ugettext as _, ugettext_lazy
 
  21 from ajaxable.utils import AjaxableFormView
 
  22 from pdcounter.models import BookStub, Author
 
  23 from pdcounter import views as pdcounter_views
 
  24 from picture.models import Picture, PictureArea
 
  25 from ssify import ssi_included, ssi_expect, SsiVariable as Var
 
  26 from suggest.forms import PublishingSuggestForm
 
  27 from catalogue import constants
 
  28 from catalogue import forms
 
  29 from catalogue.helpers import get_top_level_related_tags
 
  30 from catalogue.models import Book, Collection, Tag, Fragment
 
  31 from catalogue.utils import split_tags
 
  33 staff_required = user_passes_test(lambda user: user.is_staff)
 
  36 def catalogue(request):
 
  37     return render(request, 'catalogue/catalogue.html', {
 
  38         'books': Book.objects.filter(parent=None),
 
  39         'pictures': Picture.objects.all(),
 
  40         'collections': Collection.objects.all(),
 
  41         'active_menu_item': 'all_works',
 
  45 def book_list(request, filters=None, template_name='catalogue/book_list.html',
 
  46               nav_template_name='catalogue/snippets/book_list_nav.html',
 
  47               list_template_name='catalogue/snippets/book_list.html'):
 
  48     """ generates a listing of all books, optionally filtered """
 
  49     books_by_author, orphans, books_by_parent = Book.book_list(filters)
 
  50     books_nav = OrderedDict()
 
  51     for tag in books_by_author:
 
  52         if books_by_author[tag]:
 
  53             books_nav.setdefault(tag.sort_key[0], []).append(tag)
 
  54     # WTF: dlaczego nie include?
 
  55     return render_to_response(template_name, {
 
  56         'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
 
  57         'rendered_book_list': render_to_string(list_template_name, {
 
  58             'books_by_author': books_by_author,
 
  60             'books_by_parent': books_by_parent,
 
  62     }, context_instance=RequestContext(request))
 
  65 def daisy_list(request):
 
  66     return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
 
  69 def collection(request, slug):
 
  70     coll = get_object_or_404(Collection, slug=slug)
 
  71     return render(request, 'catalogue/collection.html', {'collection': coll})
 
  74 def differentiate_tags(request, tags, ambiguous_slugs):
 
  75     beginning = '/'.join(tag.url_chunk for tag in tags)
 
  76     unparsed = '/'.join(ambiguous_slugs[1:])
 
  78     for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
 
  80             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
 
  83     return render_to_response(
 
  84         'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
 
  85         context_instance=RequestContext(request))
 
  88 def object_list(request, objects, fragments=None, related_tags=None, tags=None, list_type='books', extra=None):
 
  91     tag_ids = [tag.pk for tag in tags]
 
  93     related_tag_lists = []
 
  95         related_tag_lists.append(related_tags)
 
  97         related_tag_lists.append(
 
  98             Tag.objects.usage_for_queryset(objects, counts=True).exclude(category='set').exclude(pk__in=tag_ids))
 
  99     if not (extra and extra.get('theme_is_set')):
 
 100         if fragments is None:
 
 101             if list_type == 'gallery':
 
 102                 fragments = PictureArea.objects.filter(picture__in=objects)
 
 104                 fragments = Fragment.objects.filter(book__in=objects)
 
 105         related_tag_lists.append(
 
 106             Tag.objects.usage_for_queryset(fragments, counts=True).filter(category='theme').exclude(pk__in=tag_ids))
 
 108     categories = split_tags(*related_tag_lists)
 
 110     objects = list(objects)
 
 112     if not objects and len(tags) == 1 and list_type == 'books':
 
 113         if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
 
 114             return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
 
 117         best = random.sample(objects, 3)
 
 122         'object_list': objects,
 
 123         'categories': categories,
 
 124         'list_type': list_type,
 
 127         'formats_form': forms.DownloadFormatsForm(),
 
 129         'active_menu_item': list_type,
 
 133     return render_to_response(
 
 134         'catalogue/tagged_object_list.html', result,
 
 135         context_instance=RequestContext(request))
 
 138 def literature(request):
 
 139     books = Book.objects.filter(parent=None)
 
 141     # last_published = Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:20]
 
 142     # most_popular = Book.objects.exclude(cover_thumb='')\
 
 143     #                    .order_by('-popularity__count', 'sort_key_author', 'sort_key')[:20]
 
 144     return object_list(request, books, related_tags=get_top_level_related_tags([]))
 
 146     #     'last_published': last_published,
 
 147     #     'most_popular': most_popular,
 
 151 def gallery(request):
 
 152     return object_list(request, Picture.objects.all(), list_type='gallery')
 
 155 def audiobooks(request):
 
 156     audiobooks = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct()
 
 157     return object_list(request, audiobooks, list_type='audiobooks', extra={
 
 158         'daisy': Book.objects.filter(media__type='daisy').distinct(),
 
 162 class ResponseInstead(Exception):
 
 163     def __init__(self, response):
 
 164         super(ResponseInstead, self).__init__()
 
 165         self.response = response
 
 168 def analyse_tags(request, tag_str):
 
 170         tags = Tag.get_tag_list(tag_str)
 
 171     except Tag.DoesNotExist:
 
 172         # Perhaps the user is asking about an author in Public Domain
 
 173         # counter (they are not represented in tags)
 
 174         chunks = tag_str.split('/')
 
 175         if len(chunks) == 2 and chunks[0] == 'autor':
 
 176             raise ResponseInstead(pdcounter_views.author_detail(request, chunks[1]))
 
 179     except Tag.MultipleObjectsReturned, e:
 
 180         # Ask the user to disambiguate
 
 181         raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
 
 182     except Tag.UrlDeprecationWarning, e:
 
 183         raise ResponseInstead(HttpResponsePermanentRedirect(
 
 184             reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
 
 187         if len(tags) > settings.MAX_TAG_LIST:
 
 189     except AttributeError:
 
 195 def theme_list(request, tags, list_type):
 
 196     shelf_tags = [tag for tag in tags if tag.category == 'set']
 
 197     fragment_tags = [tag for tag in tags if tag.category != 'set']
 
 198     if list_type == 'gallery':
 
 199         fragments = PictureArea.tagged.with_all(fragment_tags)
 
 201         fragments = Fragment.tagged.with_all(fragment_tags)
 
 204         # TODO: Pictures on shelves not supported yet.
 
 205         books = Book.tagged.with_all(shelf_tags).order_by()
 
 206         fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
 
 208     if not fragments and len(tags) == 1 and list_type == 'books':
 
 209         if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
 
 210             return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
 
 212     return object_list(request, fragments, tags=tags, list_type=list_type, extra={
 
 213         'theme_is_set': True,
 
 214         'active_menu_item': 'theme',
 
 218 def tagged_object_list(request, tags, list_type):
 
 220         tags = analyse_tags(request, tags)
 
 221     except ResponseInstead as e:
 
 224     if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
 
 227     if any(tag.category in ('theme', 'thing') for tag in tags):
 
 228         return theme_list(request, tags, list_type=list_type)
 
 230     if list_type == 'books':
 
 231         books = Book.tagged.with_all(tags)
 
 233         if any(tag.category == 'set' for tag in tags):
 
 234             params = {'objects': books}
 
 237                 'objects': Book.tagged_top_level(tags),
 
 238                 'fragments': Fragment.objects.filter(book__in=books),
 
 239                 'related_tags': get_top_level_related_tags(tags),
 
 241     elif list_type == 'gallery':
 
 242         params = {'objects': Picture.tagged.with_all(tags)}
 
 243     elif list_type == 'audiobooks':
 
 244         audiobooks = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct()
 
 246             'objects': Book.tagged.with_all(tags, audiobooks),
 
 248                 'daisy': Book.tagged.with_all(tags, audiobooks.filter(media__type='daisy').distinct()),
 
 254     return object_list(request, tags=tags, list_type=list_type, **params)
 
 257 def book_fragments(request, slug, theme_slug):
 
 258     book = get_object_or_404(Book, slug=slug)
 
 259     theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
 
 260     fragments = Fragment.tagged.with_all([theme]).filter(
 
 261         Q(book=book) | Q(book__ancestor=book))
 
 263     return render_to_response('catalogue/book_fragments.html', {
 
 266         'fragments': fragments,
 
 267         'active_menu_item': 'books',
 
 268     }, context_instance=RequestContext(request))
 
 271 def book_detail(request, slug):
 
 273         book = Book.objects.get(slug=slug)
 
 274     except Book.DoesNotExist:
 
 275         return pdcounter_views.book_stub_detail(request, slug)
 
 277     return render_to_response('catalogue/book_detail.html', {
 
 279         'tags': book.tags.exclude(category__in=('set', 'theme')),
 
 280         'book_children': book.children.all().order_by('parent_number', 'sort_key'),
 
 281         'active_menu_item': 'books',
 
 282     }, context_instance=RequestContext(request))
 
 285 def get_audiobooks(book):
 
 287     for m in book.media.filter(type='ogg').order_by().iterator():
 
 288         ogg_files[m.name] = m
 
 293     for mp3 in book.media.filter(type='mp3').iterator():
 
 294         # ogg files are always from the same project
 
 295         meta = mp3.extra_info
 
 296         project = meta.get('project')
 
 299             project = u'CzytamySłuchając'
 
 301         projects.add((project, meta.get('funded_by', '')))
 
 305         ogg = ogg_files.get(mp3.name)
 
 310         audiobooks.append(media)
 
 312     projects = sorted(projects)
 
 313     return audiobooks, projects, have_oggs
 
 316 # używane w publicznym interfejsie
 
 317 def player(request, slug):
 
 318     book = get_object_or_404(Book, slug=slug)
 
 319     if not book.has_media('mp3'):
 
 322     audiobooks, projects, have_oggs = get_audiobooks(book)
 
 324     return render_to_response('catalogue/player.html', {
 
 327         'audiobooks': audiobooks,
 
 328         'projects': projects,
 
 329     }, context_instance=RequestContext(request))
 
 332 def book_text(request, slug):
 
 333     book = get_object_or_404(Book, slug=slug)
 
 335     if not book.has_html_file():
 
 337     return render_to_response('catalogue/book_text.html', {'book': book}, context_instance=RequestContext(request))
 
 344 def _no_diacritics_regexp(query):
 
 345     """ returns a regexp for searching for a query without diacritics
 
 347     should be locale-aware """
 
 349         u'a': u'aąĄ', u'c': u'cćĆ', u'e': u'eęĘ', u'l': u'lłŁ', u'n': u'nńŃ', u'o': u'oóÓ', u's': u'sśŚ',
 
 351         u'ą': u'ąĄ', u'ć': u'ćĆ', u'ę': u'ęĘ', u'ł': u'łŁ', u'ń': u'ńŃ', u'ó': u'óÓ', u'ś': u'śŚ', u'ź': u'źŹ',
 
 357         return u"(?:%s)" % '|'.join(names[l])
 
 359     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
 
 362 def unicode_re_escape(query):
 
 363     """ Unicode-friendly version of re.escape """
 
 364     return re.sub(r'(?u)(\W)', r'\\\1', query)
 
 367 def _word_starts_with(name, prefix):
 
 368     """returns a Q object getting models having `name` contain a word
 
 369     starting with `prefix`
 
 371     We define word characters as alphanumeric and underscore, like in JS.
 
 373     Works for MySQL, PostgreSQL, Oracle.
 
 374     For SQLite, _sqlite* version is substituted for this.
 
 378     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
 
 379     # can't use [[:<:]] (word start),
 
 380     # but we want both `xy` and `(xy` to catch `(xyz)`
 
 381     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
 
 386 def _word_starts_with_regexp(prefix):
 
 387     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
 
 388     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
 
 391 def _sqlite_word_starts_with(name, prefix):
 
 392     """ version of _word_starts_with for SQLite
 
 394     SQLite in Django uses Python re module
 
 396     kwargs = {'%s__iregex' % name: _word_starts_with_regexp(prefix)}
 
 400 if hasattr(settings, 'DATABASES'):
 
 401     if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
 
 402         _word_starts_with = _sqlite_word_starts_with
 
 403 elif settings.DATABASE_ENGINE == 'sqlite3':
 
 404     _word_starts_with = _sqlite_word_starts_with
 
 408     def __init__(self, name, view):
 
 411         self.lower = name.lower()
 
 412         self.category = 'application'
 
 415         return reverse(*self._view)
 
 418     App(u'Leśmianator', (u'lesmianator', )),
 
 422 def _tags_starting_with(prefix, user=None):
 
 423     prefix = prefix.lower()
 
 425     book_stubs = BookStub.objects.filter(_word_starts_with('title', prefix))
 
 426     authors = Author.objects.filter(_word_starts_with('name', prefix))
 
 428     books = Book.objects.filter(_word_starts_with('title', prefix))
 
 429     tags = Tag.objects.filter(_word_starts_with('name', prefix))
 
 430     if user and user.is_authenticated():
 
 431         tags = tags.filter(~Q(category='set') | Q(user=user))
 
 433         tags = tags.exclude(category='set')
 
 435     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
 
 436     return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + \
 
 440 def _get_result_link(match, tag_list):
 
 441     if isinstance(match, Tag):
 
 442         return reverse('catalogue.views.tagged_object_list',
 
 443                        kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])})
 
 444     elif isinstance(match, App):
 
 447         return match.get_absolute_url()
 
 450 def _get_result_type(match):
 
 451     if isinstance(match, Book) or isinstance(match, BookStub):
 
 454         match_type = match.category
 
 458 def books_starting_with(prefix):
 
 459     prefix = prefix.lower()
 
 460     return Book.objects.filter(_word_starts_with('title', prefix))
 
 463 def find_best_matches(query, user=None):
 
 464     """ Finds a Book, Tag, BookStub or Author best matching a query.
 
 467       - zero elements when nothing is found,
 
 468       - one element when a best result is found,
 
 469       - more then one element on multiple exact matches
 
 471     Raises a ValueError on too short a query.
 
 474     query = query.lower()
 
 476         raise ValueError("query must have at least two characters")
 
 478     result = tuple(_tags_starting_with(query, user))
 
 479     # remove pdcounter stuff
 
 480     book_titles = set(match.pretty_title().lower() for match in result
 
 481                       if isinstance(match, Book))
 
 482     authors = set(match.name.lower() for match in result
 
 483                   if isinstance(match, Tag) and match.category == 'author')
 
 484     result = tuple(res for res in result if not (
 
 485                  (isinstance(res, BookStub) and res.pretty_title().lower() in book_titles) or
 
 486                  (isinstance(res, Author) and res.name.lower() in authors)
 
 489     exact_matches = tuple(res for res in result if res.name.lower() == query)
 
 493         return tuple(result)[:1]
 
 497     tags = request.GET.get('tags', '')
 
 498     prefix = request.GET.get('q', '')
 
 501         tag_list = Tag.get_tag_list(tags)
 
 502     except (Tag.DoesNotExist, Tag.MultipleObjectsReturned, Tag.UrlDeprecationWarning):
 
 506         result = find_best_matches(prefix, request.user)
 
 508         return render_to_response(
 
 509             'catalogue/search_too_short.html', {'tags': tag_list, 'prefix': prefix},
 
 510             context_instance=RequestContext(request))
 
 513         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
 
 514     elif len(result) > 1:
 
 515         return render_to_response(
 
 516             'catalogue/search_multiple_hits.html',
 
 518                 'tags': tag_list, 'prefix': prefix,
 
 519                 'results': ((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)
 
 521             context_instance=RequestContext(request))
 
 523         form = PublishingSuggestForm(initial={"books": prefix + ", "})
 
 524         return render_to_response(
 
 525             'catalogue/search_no_hits.html',
 
 526             {'tags': tag_list, 'prefix': prefix, "pubsuggest_form": form},
 
 527             context_instance=RequestContext(request))
 
 530 def tags_starting_with(request):
 
 531     prefix = request.GET.get('q', '')
 
 532     # Prefix must have at least 2 characters
 
 534         return HttpResponse('')
 
 537     for tag in _tags_starting_with(prefix, request.user):
 
 538         if tag.name not in tags_list:
 
 539             result += "\n" + tag.name
 
 540             tags_list.append(tag.name)
 
 541     return HttpResponse(result)
 
 544 def json_tags_starting_with(request, callback=None):
 
 546     prefix = request.GET.get('q', '')
 
 547     callback = request.GET.get('callback', '')
 
 548     # Prefix must have at least 2 characters
 
 550         return HttpResponse('')
 
 552     for tag in _tags_starting_with(prefix, request.user):
 
 553         if tag.name not in tags_list:
 
 554             tags_list.append(tag.name)
 
 555     if request.GET.get('mozhint', ''):
 
 556         result = [prefix, tags_list]
 
 558         result = {"matches": tags_list}
 
 559     response = JsonResponse(result, safe=False)
 
 561         response.content = callback + "(" + response.content + ");"
 
 570 def import_book(request):
 
 571     """docstring for import_book"""
 
 572     book_import_form = forms.BookImportForm(request.POST, request.FILES)
 
 573     if book_import_form.is_valid():
 
 575             book_import_form.save()
 
 580             info = sys.exc_info()
 
 581             exception = pprint.pformat(info[1])
 
 582             tb = '\n'.join(traceback.format_tb(info[2]))
 
 584                     _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
 
 585                     mimetype='text/plain')
 
 586         return HttpResponse(_("Book imported successfully"))
 
 588         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
 
 593 def book_info(request, book_id, lang='pl'):
 
 594     book = get_object_or_404(Book, id=book_id)
 
 595     # set language by hand
 
 596     translation.activate(lang)
 
 597     return render_to_response('catalogue/book_info.html', {'book': book}, context_instance=RequestContext(request))
 
 600 def tag_info(request, tag_id):
 
 601     tag = get_object_or_404(Tag, id=tag_id)
 
 602     return HttpResponse(tag.description)
 
 605 def download_zip(request, format, slug=None):
 
 606     if format in Book.ebook_formats:
 
 607         url = Book.zip_format(format)
 
 608     elif format in ('mp3', 'ogg') and slug is not None:
 
 609         book = get_object_or_404(Book, slug=slug)
 
 610         url = book.zip_audiobooks(format)
 
 612         raise Http404('No format specified for zip package')
 
 613     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
 
 616 class CustomPDFFormView(AjaxableFormView):
 
 617     form_class = forms.CustomPDFForm
 
 618     title = ugettext_lazy('Download custom PDF')
 
 619     submit = ugettext_lazy('Download')
 
 622     def __call__(self, *args, **kwargs):
 
 623         if settings.NO_CUSTOM_PDF:
 
 624             raise Http404('Custom PDF is disabled')
 
 625         return super(CustomPDFFormView, self).__call__(*args, **kwargs)
 
 627     def form_args(self, request, obj):
 
 628         """Override to parse view args and give additional args to the form."""
 
 631     def get_object(self, request, slug, *args, **kwargs):
 
 632         return get_object_or_404(Book, slug=slug)
 
 634     def context_description(self, request, obj):
 
 635         return obj.pretty_title()
 
 644 def book_mini(request, pk, with_link=True):
 
 645     # book = get_object_or_404(Book, pk=pk)
 
 647         book = Book.objects.only('cover_thumb', 'title', 'language', 'slug').get(pk=pk)
 
 648     except Book.DoesNotExist:
 
 650     return render(request, 'catalogue/book_mini_box.html', {
 
 652         'no_link': not with_link,
 
 656 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
 
 657         ('ssify.get_csrf_token',),
 
 658         ('social_tags.likes_book', (ipk,)),
 
 659         ('social_tags.book_shelf_tags', (ipk,)),
 
 660     ))(ssi_expect(pk, int)))
 
 661 def book_short(request, pk):
 
 662     book = get_object_or_404(Book, pk=pk)
 
 663     stage_note, stage_note_url = book.stage_note()
 
 664     audiobooks, projects, have_oggs = get_audiobooks(book)
 
 666     return render(request, 'catalogue/book_short.html', {
 
 668         'has_audio': book.has_media('mp3'),
 
 669         'main_link': book.get_absolute_url(),
 
 670         'parents': book.parents(),
 
 671         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
 
 672         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
 
 673         'stage_note': stage_note,
 
 674         'stage_note_url': stage_note_url,
 
 675         'audiobooks': audiobooks,
 
 676         'have_oggs': have_oggs,
 
 681     get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
 
 683         ('social_tags.choose_cite', [ipk]),
 
 684         ('catalogue_tags.choose_fragment', [ipk], {
 
 685             'unless': Var('social_tags.choose_cite', [ipk])}),
 
 686     ))(ssi_expect(pk, int)))
 
 687 def book_wide(request, pk):
 
 688     book = get_object_or_404(Book, pk=pk)
 
 689     stage_note, stage_note_url = book.stage_note()
 
 690     extra_info = book.extra_info
 
 691     audiobooks, projects, have_oggs = get_audiobooks(book)
 
 693     return render(request, 'catalogue/book_wide.html', {
 
 695         'has_audio': book.has_media('mp3'),
 
 696         'parents': book.parents(),
 
 697         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
 
 698         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
 
 699         'stage_note': stage_note,
 
 700         'stage_note_url': stage_note_url,
 
 702         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
 
 703         'extra_info': extra_info,
 
 704         'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
 
 705         'audiobooks': audiobooks,
 
 706         'have_oggs': have_oggs,
 
 711 def fragment_short(request, pk):
 
 712     fragment = get_object_or_404(Fragment, pk=pk)
 
 713     return render(request, 'catalogue/fragment_short.html', {'fragment': fragment})
 
 717 def fragment_promo(request, pk):
 
 718     fragment = get_object_or_404(Fragment, pk=pk)
 
 719     return render(request, 'catalogue/fragment_promo.html', {'fragment': fragment})
 
 723 def tag_box(request, pk):
 
 724     tag = get_object_or_404(Tag, pk=pk)
 
 725     assert tag.category != 'set'
 
 727     return render(request, 'catalogue/tag_box.html', {
 
 733 def collection_box(request, pk):
 
 734     obj = get_object_or_404(Collection, pk=pk)
 
 736     return render(request, 'catalogue/collection_box.html', {
 
 741 def tag_catalogue(request, category):
 
 742     if category == 'theme':
 
 743         tags = Tag.objects.usage_for_model(
 
 744             Fragment, counts=True).filter(category='theme')
 
 746         tags = list(get_top_level_related_tags((), categories=(category,)))
 
 748     described_tags = [tag for tag in tags if tag.description]
 
 750     if len(described_tags) > 4:
 
 751         best = random.sample(described_tags, 4)
 
 753         best = described_tags
 
 755     return render(request, 'catalogue/tag_catalogue.html', {
 
 758         'title': constants.CATEGORIES_NAME_PLURAL[category],
 
 759         'whole_category': constants.WHOLE_CATEGORY[category],
 
 760         'active_menu_item': 'theme' if category == 'theme' else None,
 
 764 def collections(request):
 
 765     objects = Collection.objects.all()
 
 768         best = random.sample(objects, 3)
 
 772     return render(request, 'catalogue/collections.html', {