c2636089dc2bd95d0df91defcc9aac2629bb5ef6
[wolnelektury.git] / src / catalogue / views.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 collections import OrderedDict
6 import re
7 import random
8
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
20
21 from ajaxable.utils import AjaxableFormView
22 from pdcounter import models as pdcounter_models
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 V
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 import models
31 from catalogue.utils import split_tags
32
33 staff_required = user_passes_test(lambda user: user.is_staff)
34
35
36 def catalogue(request, as_json=False):
37     books = models.Book.objects.filter(parent=None).order_by('sort_key_author', 'sort_key')
38     pictures = Picture.objects.order_by('sort_key_author', 'sort_key')
39     collections = models.Collection.objects.all()
40     return render(request, 'catalogue/catalogue.html', locals())
41
42
43 def book_list(request, filter=None, get_filter=None, template_name='catalogue/book_list.html',
44               nav_template_name='catalogue/snippets/book_list_nav.html',
45               list_template_name='catalogue/snippets/book_list.html', context=None):
46     """ generates a listing of all books, optionally filtered with a test function """
47     if get_filter:
48         filter = get_filter()
49     books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
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     rendered_nav = render_to_string(nav_template_name, locals())
55     rendered_book_list = render_to_string(list_template_name, locals())
56     return render_to_response(template_name, locals(), context_instance=RequestContext(request))
57
58
59 def audiobook_list(request):
60     books = models.Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct().order_by(
61         'sort_key_author', 'sort_key')
62     books = list(books)
63     if len(books) > 3:
64         best = random.sample(books, 3)
65     else:
66         best = books
67
68     daisy = models.Book.objects.filter(media__type='daisy').distinct().order_by('sort_key_author', 'sort_key')
69
70     return render(request, 'catalogue/audiobook_list.html', {
71         'books': books,
72         'best': best,
73         'daisy': daisy,
74         })
75
76
77 def daisy_list(request):
78     return book_list(request, Q(media__type='daisy'),
79                      template_name='catalogue/daisy_list.html',
80                      )
81
82
83 def collection(request, slug):
84     coll = get_object_or_404(models.Collection, slug=slug)
85     return render(request, 'catalogue/collection.html', {'collection': coll})
86
87
88 def differentiate_tags(request, tags, ambiguous_slugs):
89     beginning = '/'.join(tag.url_chunk for tag in tags)
90     unparsed = '/'.join(ambiguous_slugs[1:])
91     options = []
92     for tag in models.Tag.objects.filter(slug=ambiguous_slugs[0]):
93         options.append({
94             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
95             'tags': [tag]
96         })
97     return render_to_response(
98         'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
99         context_instance=RequestContext(request))
100
101
102 # TODO: Rewrite this hellish piece of code which tries to do everything
103 def tagged_object_list(request, tags='', gallery=False):
104     raw_tags = tags
105     # preliminary tests and conditions
106     try:
107         tags = models.Tag.get_tag_list(tags)
108     except models.Tag.DoesNotExist:
109         # Perhaps the user is asking about an author in Public Domain
110         # counter (they are not represented in tags)
111         chunks = tags.split('/')
112         if len(chunks) == 2 and chunks[0] == 'autor':
113             return pdcounter_views.author_detail(request, chunks[1])
114         else:
115             raise Http404
116     except models.Tag.MultipleObjectsReturned, e:
117         # Ask the user to disambiguate
118         return differentiate_tags(request, e.tags, e.ambiguous_slugs)
119     except models.Tag.UrlDeprecationWarning, e:
120         return HttpResponsePermanentRedirect(
121             reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
122
123     try:
124         if len(tags) > settings.MAX_TAG_LIST:
125             raise Http404
126     except AttributeError:
127         pass
128
129     # beginning of digestion
130     theme_is_set = [tag for tag in tags if tag.category == 'theme']
131     shelf_is_set = [tag for tag in tags if tag.category == 'set']
132     only_shelf = shelf_is_set and len(tags) == 1
133     only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
134     tags_pks = [tag.pk for tag in tags]
135
136     objects = None
137
138     if theme_is_set:
139         # Only fragments (or pirctureareas) here.
140         shelf_tags = [tag for tag in tags if tag.category == 'set']
141         fragment_tags = [tag for tag in tags if tag.category != 'set']
142         if gallery:
143             fragments = PictureArea.tagged.with_all(fragment_tags)
144         else:
145             fragments = models.Fragment.tagged.with_all(fragment_tags)
146
147         if shelf_tags:
148             if gallery:
149                 # TODO: Pictures on shelves not supported yet.
150                 raise Http404
151             else:
152                 books = models.Book.tagged.with_all(shelf_tags).order_by()
153                 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
154
155         categories = split_tags(
156             models.Tag.objects.usage_for_queryset(fragments, counts=True).exclude(pk__in=tags_pks),
157         )
158
159         objects = fragments
160     else:
161         if gallery:
162             if shelf_is_set:
163                 # TODO: Pictures on shelves not supported yet.
164                 raise Http404
165             else:
166                 if tags:
167                     objects = Picture.tagged.with_all(tags)
168                 else:
169                     objects = Picture.objects.all()
170             areas = PictureArea.objects.filter(picture__in=objects)
171             categories = split_tags(
172                 models.Tag.objects.usage_for_queryset(
173                     objects, counts=True).exclude(pk__in=tags_pks),
174                 models.Tag.objects.usage_for_queryset(
175                     areas, counts=True).filter(
176                     category__in=('theme', 'thing')).exclude(
177                     pk__in=tags_pks),
178             )
179         else:
180             if tags:
181                 all_books = models.Book.tagged.with_all(tags)
182             else:
183                 all_books = models.Book.objects.filter(parent=None)
184             if shelf_is_set:
185                 objects = all_books
186                 related_book_tags = models.Tag.objects.usage_for_queryset(
187                     objects, counts=True).exclude(
188                     category='set').exclude(pk__in=tags_pks)
189             else:
190                 if tags:
191                     objects = models.Book.tagged_top_level(tags)
192                 else:
193                     objects = all_books
194                 # WTF: was outside if, overwriting value assigned if shelf_is_set
195                 related_book_tags = get_top_level_related_tags(tags)
196
197             fragments = models.Fragment.objects.filter(book__in=all_books)
198
199             categories = split_tags(
200                 related_book_tags,
201                 models.Tag.objects.usage_for_queryset(
202                     fragments, counts=True).filter(
203                     category='theme').exclude(pk__in=tags_pks),
204             )
205         objects = objects.order_by('sort_key_author', 'sort_key')
206
207     objects = list(objects)
208     if len(objects) > 3:
209         best = random.sample(objects, 3)
210     else:
211         best = objects
212
213     if not gallery and not objects and len(tags) == 1:
214         tag = tags[0]
215         if (tag.category in ('theme', 'thing') and PictureArea.tagged.with_any([tag]).exists() or
216                 Picture.tagged.with_any([tag]).exists()):
217             return redirect('tagged_object_list_gallery', raw_tags, permanent=False)
218
219     return render_to_response(
220         'catalogue/tagged_object_list.html',
221         {
222             'object_list': objects,
223             'categories': categories,
224             'only_shelf': only_shelf,
225             'only_my_shelf': only_my_shelf,
226             'formats_form': forms.DownloadFormatsForm(),
227             'tags': tags,
228             'tag_ids': tags_pks,
229             'theme_is_set': theme_is_set,
230             'best': best,
231             'gallery': gallery,
232         },
233         context_instance=RequestContext(request))
234
235
236 def book_fragments(request, slug, theme_slug):
237     book = get_object_or_404(models.Book, slug=slug)
238     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
239     fragments = models.Fragment.tagged.with_all([theme]).filter(
240         Q(book=book) | Q(book__ancestor=book))
241
242     return render_to_response('catalogue/book_fragments.html', locals(), context_instance=RequestContext(request))
243
244
245 def book_detail(request, slug):
246     try:
247         book = models.Book.objects.get(slug=slug)
248     except models.Book.DoesNotExist:
249         return pdcounter_views.book_stub_detail(request, slug)
250
251     tags = book.tags.exclude(category__in=('set', 'theme'))
252     book_children = book.children.all().order_by('parent_number', 'sort_key')
253     return render_to_response('catalogue/book_detail.html', locals(), context_instance=RequestContext(request))
254
255
256 def get_audiobooks(book):
257     ogg_files = {}
258     for m in book.media.filter(type='ogg').order_by().iterator():
259         ogg_files[m.name] = m
260
261     audiobooks = []
262     have_oggs = True
263     projects = set()
264     for mp3 in book.media.filter(type='mp3').iterator():
265         # ogg files are always from the same project
266         meta = mp3.extra_info
267         project = meta.get('project')
268         if not project:
269             # temporary fallback
270             project = u'CzytamySłuchając'
271
272         projects.add((project, meta.get('funded_by', '')))
273
274         media = {'mp3': mp3}
275
276         ogg = ogg_files.get(mp3.name)
277         if ogg:
278             media['ogg'] = ogg
279         else:
280             have_oggs = False
281         audiobooks.append(media)
282
283     projects = sorted(projects)
284     return audiobooks, projects, have_oggs
285
286
287 def player(request, slug):
288     book = get_object_or_404(models.Book, slug=slug)
289     if not book.has_media('mp3'):
290         raise Http404
291
292     audiobooks, projects, have_oggs = get_audiobooks(book)
293
294     extra_info = book.extra_info
295
296     return render_to_response('catalogue/player.html', locals(), context_instance=RequestContext(request))
297
298
299 def book_text(request, slug):
300     book = get_object_or_404(models.Book, slug=slug)
301
302     if not book.has_html_file():
303         raise Http404
304     return render_to_response('catalogue/book_text.html', locals(), context_instance=RequestContext(request))
305
306
307 # ==========
308 # = Search =
309 # ==========
310
311 def _no_diacritics_regexp(query):
312     """ returns a regexp for searching for a query without diacritics
313
314     should be locale-aware """
315     names = {
316         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śŚ',
317         u'z': u'zźżŹŻ',
318         u'ą': u'ąĄ', u'ć': u'ćĆ', u'ę': u'ęĘ', u'ł': u'łŁ', u'ń': u'ńŃ', u'ó': u'óÓ', u'ś': u'śŚ', u'ź': u'źŹ',
319         u'ż': u'żŻ'
320         }
321
322     def repl(m):
323         l = m.group()
324         return u"(?:%s)" % '|'.join(names[l])
325
326     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
327
328
329 def unicode_re_escape(query):
330     """ Unicode-friendly version of re.escape """
331     return re.sub(r'(?u)(\W)', r'\\\1', query)
332
333
334 def _word_starts_with(name, prefix):
335     """returns a Q object getting models having `name` contain a word
336     starting with `prefix`
337
338     We define word characters as alphanumeric and underscore, like in JS.
339
340     Works for MySQL, PostgreSQL, Oracle.
341     For SQLite, _sqlite* version is substituted for this.
342     """
343     kwargs = {}
344
345     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
346     # can't use [[:<:]] (word start),
347     # but we want both `xy` and `(xy` to catch `(xyz)`
348     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
349
350     return Q(**kwargs)
351
352
353 def _word_starts_with_regexp(prefix):
354     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
355     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
356
357
358 def _sqlite_word_starts_with(name, prefix):
359     """ version of _word_starts_with for SQLite
360
361     SQLite in Django uses Python re module
362     """
363     kwargs = {'%s__iregex' % name: _word_starts_with_regexp(prefix)}
364     return Q(**kwargs)
365
366
367 if hasattr(settings, 'DATABASES'):
368     if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
369         _word_starts_with = _sqlite_word_starts_with
370 elif settings.DATABASE_ENGINE == 'sqlite3':
371     _word_starts_with = _sqlite_word_starts_with
372
373
374 class App:
375     def __init__(self, name, view):
376         self.name = name
377         self._view = view
378         self.lower = name.lower()
379         self.category = 'application'
380
381     def view(self):
382         return reverse(*self._view)
383
384 _apps = (
385     App(u'Leśmianator', (u'lesmianator', )),
386     )
387
388
389 def _tags_starting_with(prefix, user=None):
390     prefix = prefix.lower()
391     # PD counter
392     book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
393     authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
394
395     books = models.Book.objects.filter(_word_starts_with('title', prefix))
396     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
397     if user and user.is_authenticated():
398         tags = tags.filter(~Q(category='set') | Q(user=user))
399     else:
400         tags = tags.exclude(category='set')
401
402     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
403     return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + \
404         list(authors)
405
406
407 def _get_result_link(match, tag_list):
408     if isinstance(match, models.Tag):
409         return reverse('catalogue.views.tagged_object_list',
410                        kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])})
411     elif isinstance(match, App):
412         return match.view()
413     else:
414         return match.get_absolute_url()
415
416
417 def _get_result_type(match):
418     if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
419         match_type = 'book'
420     else:
421         match_type = match.category
422     return match_type
423
424
425 def books_starting_with(prefix):
426     prefix = prefix.lower()
427     return models.Book.objects.filter(_word_starts_with('title', prefix))
428
429
430 def find_best_matches(query, user=None):
431     """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
432
433     Returns a with:
434       - zero elements when nothing is found,
435       - one element when a best result is found,
436       - more then one element on multiple exact matches
437
438     Raises a ValueError on too short a query.
439     """
440
441     query = query.lower()
442     if len(query) < 2:
443         raise ValueError("query must have at least two characters")
444
445     result = tuple(_tags_starting_with(query, user))
446     # remove pdcounter stuff
447     book_titles = set(match.pretty_title().lower() for match in result
448                       if isinstance(match, models.Book))
449     authors = set(match.name.lower() for match in result
450                   if isinstance(match, models.Tag) and match.category == 'author')
451     result = tuple(res for res in result if not (
452                  (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles) or
453                  (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
454              ))
455
456     exact_matches = tuple(res for res in result if res.name.lower() == query)
457     if exact_matches:
458         return exact_matches
459     else:
460         return tuple(result)[:1]
461
462
463 def search(request):
464     tags = request.GET.get('tags', '')
465     prefix = request.GET.get('q', '')
466
467     try:
468         tag_list = models.Tag.get_tag_list(tags)
469     except (models.Tag.DoesNotExist, models.Tag.MultipleObjectsReturned, models.Tag.UrlDeprecationWarning):
470         tag_list = []
471
472     try:
473         result = find_best_matches(prefix, request.user)
474     except ValueError:
475         return render_to_response(
476             'catalogue/search_too_short.html', {'tags': tag_list, 'prefix': prefix},
477             context_instance=RequestContext(request))
478
479     if len(result) == 1:
480         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
481     elif len(result) > 1:
482         return render_to_response(
483             'catalogue/search_multiple_hits.html',
484             {
485                 'tags': tag_list, 'prefix': prefix,
486                 'results': ((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)
487             },
488             context_instance=RequestContext(request))
489     else:
490         form = PublishingSuggestForm(initial={"books": prefix + ", "})
491         return render_to_response(
492             'catalogue/search_no_hits.html',
493             {'tags': tag_list, 'prefix': prefix, "pubsuggest_form": form},
494             context_instance=RequestContext(request))
495
496
497 def tags_starting_with(request):
498     prefix = request.GET.get('q', '')
499     # Prefix must have at least 2 characters
500     if len(prefix) < 2:
501         return HttpResponse('')
502     tags_list = []
503     result = ""
504     for tag in _tags_starting_with(prefix, request.user):
505         if tag.name not in tags_list:
506             result += "\n" + tag.name
507             tags_list.append(tag.name)
508     return HttpResponse(result)
509
510
511 def json_tags_starting_with(request, callback=None):
512     # Callback for JSONP
513     prefix = request.GET.get('q', '')
514     callback = request.GET.get('callback', '')
515     # Prefix must have at least 2 characters
516     if len(prefix) < 2:
517         return HttpResponse('')
518     tags_list = []
519     for tag in _tags_starting_with(prefix, request.user):
520         if tag.name not in tags_list:
521             tags_list.append(tag.name)
522     if request.GET.get('mozhint', ''):
523         result = [prefix, tags_list]
524     else:
525         result = {"matches": tags_list}
526     response = JsonResponse(result, safe=False)
527     if callback:
528         response.content = callback + "(" + response.content + ");"
529     return response
530
531
532 # =========
533 # = Admin =
534 # =========
535 @login_required
536 @staff_required
537 def import_book(request):
538     """docstring for import_book"""
539     book_import_form = forms.BookImportForm(request.POST, request.FILES)
540     if book_import_form.is_valid():
541         try:
542             book_import_form.save()
543         except:
544             import sys
545             import pprint
546             import traceback
547             info = sys.exc_info()
548             exception = pprint.pformat(info[1])
549             tb = '\n'.join(traceback.format_tb(info[2]))
550             return HttpResponse(
551                     _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
552                     mimetype='text/plain')
553         return HttpResponse(_("Book imported successfully"))
554     else:
555         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
556
557
558 # info views for API
559
560 def book_info(request, book_id, lang='pl'):
561     book = get_object_or_404(models.Book, id=book_id)
562     # set language by hand
563     translation.activate(lang)
564     return render_to_response('catalogue/book_info.html', locals(), context_instance=RequestContext(request))
565
566
567 def tag_info(request, tag_id):
568     tag = get_object_or_404(models.Tag, id=tag_id)
569     return HttpResponse(tag.description)
570
571
572 def download_zip(request, format, slug=None):
573     if format in models.Book.ebook_formats:
574         url = models.Book.zip_format(format)
575     elif format in ('mp3', 'ogg') and slug is not None:
576         book = get_object_or_404(models.Book, slug=slug)
577         url = book.zip_audiobooks(format)
578     else:
579         raise Http404('No format specified for zip package')
580     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
581
582
583 class CustomPDFFormView(AjaxableFormView):
584     form_class = forms.CustomPDFForm
585     title = ugettext_lazy('Download custom PDF')
586     submit = ugettext_lazy('Download')
587     honeypot = True
588
589     def __call__(self, *args, **kwargs):
590         if settings.NO_CUSTOM_PDF:
591             raise Http404('Custom PDF is disabled')
592         return super(CustomPDFFormView, self).__call__(*args, **kwargs)
593
594     def form_args(self, request, obj):
595         """Override to parse view args and give additional args to the form."""
596         return (obj,), {}
597
598     def get_object(self, request, slug, *args, **kwargs):
599         return get_object_or_404(models.Book, slug=slug)
600
601     def context_description(self, request, obj):
602         return obj.pretty_title()
603
604
605 ####
606 # Includes
607 ####
608
609
610 @ssi_included
611 def book_mini(request, pk, with_link=True):
612     # book = get_object_or_404(models.Book, pk=pk)
613     try:
614         book = models.Book.objects.only('cover_thumb', 'title', 'language', 'slug').get(pk=pk)
615     except models.Book.DoesNotExist:
616         raise Http404
617     return render(request, 'catalogue/book_mini_box.html', {
618         'book': book,
619         'author': book.author_unicode(),
620         'with_link': with_link,
621         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
622     })
623
624
625 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
626         ('ssify.get_csrf_token',),
627         ('social_tags.likes_book', (ipk,)),
628         ('social_tags.book_shelf_tags', (ipk,)),
629     ))(ssi_expect(pk, int)))
630 def book_short(request, pk):
631     book = get_object_or_404(models.Book, pk=pk)
632     stage_note, stage_note_url = book.stage_note()
633     audiobooks, projects, have_oggs = get_audiobooks(book)
634
635     return render(request, 'catalogue/book_short.html', {
636         'book': book,
637         'has_audio': book.has_media('mp3'),
638         'main_link': book.get_absolute_url(),
639         'parents': book.parents(),
640         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
641         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
642         'stage_note': stage_note,
643         'stage_note_url': stage_note_url,
644         'audiobooks': audiobooks,
645         'have_oggs': have_oggs,
646     })
647
648
649 @ssi_included(
650     get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
651     (lambda ipk: (
652         ('social_tags.choose_cite', [ipk]),
653         ('catalogue_tags.choose_fragment', [ipk], {
654             'unless': V('social_tags.choose_cite', [ipk])}),
655     ))(ssi_expect(pk, int)))
656 def book_wide(request, pk):
657     book = get_object_or_404(models.Book, pk=pk)
658     stage_note, stage_note_url = book.stage_note()
659     extra_info = book.extra_info
660     audiobooks, projects, have_oggs = get_audiobooks(book)
661
662     return render(request, 'catalogue/book_wide.html', {
663         'book': book,
664         'has_audio': book.has_media('mp3'),
665         'parents': book.parents(),
666         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
667         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
668         'stage_note': stage_note,
669         'stage_note_url': stage_note_url,
670
671         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
672         'extra_info': extra_info,
673         'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
674         'audiobooks': audiobooks,
675         'have_oggs': have_oggs,
676     })
677
678
679 @ssi_included
680 def fragment_short(request, pk):
681     fragment = get_object_or_404(models.Fragment, pk=pk)
682     return render(request, 'catalogue/fragment_short.html', {'fragment': fragment})
683
684
685 @ssi_included
686 def fragment_promo(request, pk):
687     fragment = get_object_or_404(models.Fragment, pk=pk)
688     return render(request, 'catalogue/fragment_promo.html', {'fragment': fragment})
689
690
691 @ssi_included
692 def tag_box(request, pk):
693     tag = get_object_or_404(models.Tag, pk=pk)
694     assert tag.category != 'set'
695
696     return render(request, 'catalogue/tag_box.html', {
697         'tag': tag,
698     })
699
700
701 @ssi_included
702 def collection_box(request, pk):
703     obj = get_object_or_404(models.Collection, pk=pk)
704
705     return render(request, 'catalogue/collection_box.html', {
706         'obj': obj,
707     })
708
709
710 def tag_catalogue(request, category):
711     if category == 'theme':
712         tags = models.Tag.objects.usage_for_model(
713             models.Fragment, counts=True).filter(category='theme')
714     else:
715         tags = list(get_top_level_related_tags((), categories=(category,)))
716
717     described_tags = [tag for tag in tags if tag.description]
718
719     if len(described_tags) > 4:
720         best = random.sample(described_tags, 4)
721     else:
722         best = described_tags
723
724     return render(request, 'catalogue/tag_catalogue.html', {
725         'tags': tags,
726         'best': best,
727         'title': constants.CATEGORIES_NAME_PLURAL[category],
728         'whole_category': constants.WHOLE_CATEGORY[category],
729     })
730
731
732 def collections(request):
733     objects = models.Collection.objects.all()
734
735     if len(objects) > 3:
736         best = random.sample(objects, 3)
737     else:
738         best = objects
739
740     return render(request, 'catalogue/collections.html', {
741         'objects': objects,
742         'best': best,
743     })