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