2aa98f721916ee64d6225c026c1bd08af35ebee3
[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.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
32
33 staff_required = user_passes_test(lambda user: user.is_staff)
34
35
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',
42     })
43
44
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,
59             'orphans': orphans,
60             'books_by_parent': books_by_parent,
61         })
62     }, context_instance=RequestContext(request))
63
64
65 def daisy_list(request):
66     return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
67
68
69 def collection(request, slug):
70     coll = get_object_or_404(Collection, slug=slug)
71     return render(request, 'catalogue/collection.html', {'collection': coll})
72
73
74 def differentiate_tags(request, tags, ambiguous_slugs):
75     beginning = '/'.join(tag.url_chunk for tag in tags)
76     unparsed = '/'.join(ambiguous_slugs[1:])
77     options = []
78     for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
79         options.append({
80             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
81             'tags': [tag]
82         })
83     return render_to_response(
84         'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
85         context_instance=RequestContext(request))
86
87
88 def object_list(request, objects, fragments=None, related_tags=None, tags=None, list_type='books', extra=None):
89     if not tags:
90         tags = []
91     tag_ids = [tag.pk for tag in tags]
92
93     related_tag_lists = []
94     if related_tags:
95         related_tag_lists.append(related_tags)
96     else:
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)
103             else:
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))
107
108     categories = split_tags(*related_tag_lists)
109
110     objects = list(objects)
111
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))
115
116     if len(objects) > 3:
117         best = random.sample(objects, 3)
118     else:
119         best = objects
120
121     result = {
122         'object_list': objects,
123         'categories': categories,
124         'list_type': list_type,
125         'tags': tags,
126
127         'formats_form': forms.DownloadFormatsForm(),
128         'best': best,
129         'active_menu_item': list_type,
130     }
131     if extra:
132         result.update(extra)
133     return render_to_response(
134         'catalogue/tagged_object_list.html', result,
135         context_instance=RequestContext(request))
136
137
138 def literature(request):
139     books = Book.objects.filter(parent=None)
140
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([]))
145     # extra={
146     #     'last_published': last_published,
147     #     'most_popular': most_popular,
148     # })
149
150
151 def gallery(request):
152     return object_list(request, Picture.objects.all(), list_type='gallery')
153
154
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(),
159     })
160
161
162 class ResponseInstead(Exception):
163     def __init__(self, response):
164         super(ResponseInstead, self).__init__()
165         self.response = response
166
167
168 def analyse_tags(request, tag_str):
169     try:
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]))
177         else:
178             raise Http404
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)])))
185
186     try:
187         if len(tags) > settings.MAX_TAG_LIST:
188             raise Http404
189     except AttributeError:
190         pass
191
192     return tags
193
194
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)
200     else:
201         fragments = Fragment.tagged.with_all(fragment_tags)
202
203     if shelf_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))
207
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))
211
212     return object_list(request, fragments, tags=tags, list_type=list_type, extra={
213         'theme_is_set': True,
214         'active_menu_item': 'theme',
215     })
216
217
218 def tagged_object_list(request, tags, list_type):
219     try:
220         tags = analyse_tags(request, tags)
221     except ResponseInstead as e:
222         return e.response
223
224     if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
225         raise Http404
226
227     if any(tag.category in ('theme', 'thing') for tag in tags):
228         return theme_list(request, tags, list_type=list_type)
229
230     if list_type == 'books':
231         books = Book.tagged.with_all(tags)
232
233         if any(tag.category == 'set' for tag in tags):
234             params = {'objects': books}
235         else:
236             params = {
237                 'objects': Book.tagged_top_level(tags),
238                 'fragments': Fragment.objects.filter(book__in=books),
239                 'related_tags': get_top_level_related_tags(tags),
240             }
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()
245         params = {
246             'objects': Book.tagged.with_all(tags, audiobooks),
247             'extra': {
248                 'daisy': Book.tagged.with_all(tags, audiobooks.filter(media__type='daisy').distinct()),
249             }
250         }
251     else:
252         raise Http404
253
254     return object_list(request, tags=tags, list_type=list_type, **params)
255
256
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))
262
263     return render_to_response('catalogue/book_fragments.html', {
264         'book': book,
265         'theme': theme,
266         'fragments': fragments,
267         'active_menu_item': 'books',
268     }, context_instance=RequestContext(request))
269
270
271 def book_detail(request, slug):
272     try:
273         book = Book.objects.get(slug=slug)
274     except Book.DoesNotExist:
275         return pdcounter_views.book_stub_detail(request, slug)
276
277     return render_to_response('catalogue/book_detail.html', {
278         'book': book,
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))
283
284
285 def get_audiobooks(book):
286     ogg_files = {}
287     for m in book.media.filter(type='ogg').order_by().iterator():
288         ogg_files[m.name] = m
289
290     audiobooks = []
291     have_oggs = True
292     projects = set()
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')
297         if not project:
298             # temporary fallback
299             project = u'CzytamySłuchając'
300
301         projects.add((project, meta.get('funded_by', '')))
302
303         media = {'mp3': mp3}
304
305         ogg = ogg_files.get(mp3.name)
306         if ogg:
307             media['ogg'] = ogg
308         else:
309             have_oggs = False
310         audiobooks.append(media)
311
312     projects = sorted(projects)
313     return audiobooks, projects, have_oggs
314
315
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'):
320         raise Http404
321
322     audiobooks, projects, have_oggs = get_audiobooks(book)
323
324     return render_to_response('catalogue/player.html', {
325         'book': book,
326         'audiobook': '',
327         'audiobooks': audiobooks,
328         'projects': projects,
329     }, context_instance=RequestContext(request))
330
331
332 def book_text(request, slug):
333     book = get_object_or_404(Book, slug=slug)
334
335     if not book.has_html_file():
336         raise Http404
337     return render_to_response('catalogue/book_text.html', {'book': book}, context_instance=RequestContext(request))
338
339
340 # ==========
341 # = Search =
342 # ==========
343
344 def _no_diacritics_regexp(query):
345     """ returns a regexp for searching for a query without diacritics
346
347     should be locale-aware """
348     names = {
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śŚ',
350         u'z': u'zźżŹŻ',
351         u'ą': u'ąĄ', u'ć': u'ćĆ', u'ę': u'ęĘ', u'ł': u'łŁ', u'ń': u'ńŃ', u'ó': u'óÓ', u'ś': u'śŚ', u'ź': u'źŹ',
352         u'ż': u'żŻ'
353         }
354
355     def repl(m):
356         l = m.group()
357         return u"(?:%s)" % '|'.join(names[l])
358
359     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
360
361
362 def unicode_re_escape(query):
363     """ Unicode-friendly version of re.escape """
364     return re.sub(r'(?u)(\W)', r'\\\1', query)
365
366
367 def _word_starts_with(name, prefix):
368     """returns a Q object getting models having `name` contain a word
369     starting with `prefix`
370
371     We define word characters as alphanumeric and underscore, like in JS.
372
373     Works for MySQL, PostgreSQL, Oracle.
374     For SQLite, _sqlite* version is substituted for this.
375     """
376     kwargs = {}
377
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
382
383     return Q(**kwargs)
384
385
386 def _word_starts_with_regexp(prefix):
387     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
388     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
389
390
391 def _sqlite_word_starts_with(name, prefix):
392     """ version of _word_starts_with for SQLite
393
394     SQLite in Django uses Python re module
395     """
396     kwargs = {'%s__iregex' % name: _word_starts_with_regexp(prefix)}
397     return Q(**kwargs)
398
399
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
405
406
407 class App:
408     def __init__(self, name, view):
409         self.name = name
410         self._view = view
411         self.lower = name.lower()
412         self.category = 'application'
413
414     def view(self):
415         return reverse(*self._view)
416
417 _apps = (
418     App(u'Leśmianator', (u'lesmianator', )),
419     )
420
421
422 def _tags_starting_with(prefix, user=None):
423     prefix = prefix.lower()
424     # PD counter
425     book_stubs = BookStub.objects.filter(_word_starts_with('title', prefix))
426     authors = Author.objects.filter(_word_starts_with('name', prefix))
427
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))
432     else:
433         tags = tags.exclude(category='set')
434
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) + \
437         list(authors)
438
439
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):
445         return match.view()
446     else:
447         return match.get_absolute_url()
448
449
450 def _get_result_type(match):
451     if isinstance(match, Book) or isinstance(match, BookStub):
452         match_type = 'book'
453     else:
454         match_type = match.category
455     return match_type
456
457
458 def books_starting_with(prefix):
459     prefix = prefix.lower()
460     return Book.objects.filter(_word_starts_with('title', prefix))
461
462
463 def find_best_matches(query, user=None):
464     """ Finds a Book, Tag, BookStub or Author best matching a query.
465
466     Returns a with:
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
470
471     Raises a ValueError on too short a query.
472     """
473
474     query = query.lower()
475     if len(query) < 2:
476         raise ValueError("query must have at least two characters")
477
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)
487              ))
488
489     exact_matches = tuple(res for res in result if res.name.lower() == query)
490     if exact_matches:
491         return exact_matches
492     else:
493         return tuple(result)[:1]
494
495
496 def search(request):
497     tags = request.GET.get('tags', '')
498     prefix = request.GET.get('q', '')
499
500     try:
501         tag_list = Tag.get_tag_list(tags)
502     except (Tag.DoesNotExist, Tag.MultipleObjectsReturned, Tag.UrlDeprecationWarning):
503         tag_list = []
504
505     try:
506         result = find_best_matches(prefix, request.user)
507     except ValueError:
508         return render_to_response(
509             'catalogue/search_too_short.html', {'tags': tag_list, 'prefix': prefix},
510             context_instance=RequestContext(request))
511
512     if len(result) == 1:
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',
517             {
518                 'tags': tag_list, 'prefix': prefix,
519                 'results': ((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)
520             },
521             context_instance=RequestContext(request))
522     else:
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))
528
529
530 def tags_starting_with(request):
531     prefix = request.GET.get('q', '')
532     # Prefix must have at least 2 characters
533     if len(prefix) < 2:
534         return HttpResponse('')
535     tags_list = []
536     result = ""
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)
542
543
544 def json_tags_starting_with(request, callback=None):
545     # Callback for JSONP
546     prefix = request.GET.get('q', '')
547     callback = request.GET.get('callback', '')
548     # Prefix must have at least 2 characters
549     if len(prefix) < 2:
550         return HttpResponse('')
551     tags_list = []
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]
557     else:
558         result = {"matches": tags_list}
559     response = JsonResponse(result, safe=False)
560     if callback:
561         response.content = callback + "(" + response.content + ");"
562     return response
563
564
565 # =========
566 # = Admin =
567 # =========
568 @login_required
569 @staff_required
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():
574         try:
575             book_import_form.save()
576         except:
577             import sys
578             import pprint
579             import traceback
580             info = sys.exc_info()
581             exception = pprint.pformat(info[1])
582             tb = '\n'.join(traceback.format_tb(info[2]))
583             return HttpResponse(
584                     _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
585                     mimetype='text/plain')
586         return HttpResponse(_("Book imported successfully"))
587     else:
588         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
589
590
591 # info views for API
592
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))
598
599
600 def tag_info(request, tag_id):
601     tag = get_object_or_404(Tag, id=tag_id)
602     return HttpResponse(tag.description)
603
604
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)
611     else:
612         raise Http404('No format specified for zip package')
613     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
614
615
616 class CustomPDFFormView(AjaxableFormView):
617     form_class = forms.CustomPDFForm
618     title = ugettext_lazy('Download custom PDF')
619     submit = ugettext_lazy('Download')
620     honeypot = True
621
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)
626
627     def form_args(self, request, obj):
628         """Override to parse view args and give additional args to the form."""
629         return (obj,), {}
630
631     def get_object(self, request, slug, *args, **kwargs):
632         return get_object_or_404(Book, slug=slug)
633
634     def context_description(self, request, obj):
635         return obj.pretty_title()
636
637
638 ####
639 # Includes
640 ####
641
642
643 @ssi_included
644 def book_mini(request, pk, with_link=True):
645     # book = get_object_or_404(Book, pk=pk)
646     try:
647         book = Book.objects.only('cover_thumb', 'title', 'language', 'slug').get(pk=pk)
648     except Book.DoesNotExist:
649         raise Http404
650     return render(request, 'catalogue/book_mini_box.html', {
651         'book': book,
652         'no_link': not with_link,
653     })
654
655
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)
665
666     return render(request, 'catalogue/book_short.html', {
667         'book': book,
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,
677     })
678
679
680 @ssi_included(
681     get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
682     (lambda ipk: (
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)
692
693     return render(request, 'catalogue/book_wide.html', {
694         'book': book,
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,
701
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,
707     })
708
709
710 @ssi_included
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})
714
715
716 @ssi_included
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})
720
721
722 @ssi_included
723 def tag_box(request, pk):
724     tag = get_object_or_404(Tag, pk=pk)
725     assert tag.category != 'set'
726
727     return render(request, 'catalogue/tag_box.html', {
728         'tag': tag,
729     })
730
731
732 @ssi_included
733 def collection_box(request, pk):
734     collection = get_object_or_404(Collection, pk=pk)
735
736     return render(request, 'catalogue/collection_box.html', {
737         'collection': collection,
738     })
739
740
741 def tag_catalogue(request, category):
742     if category == 'theme':
743         tags = Tag.objects.usage_for_model(
744             Fragment, counts=True).filter(category='theme')
745     else:
746         tags = list(get_top_level_related_tags((), categories=(category,)))
747
748     described_tags = [tag for tag in tags if tag.description]
749
750     if len(described_tags) > 4:
751         best = random.sample(described_tags, 4)
752     else:
753         best = described_tags
754
755     return render(request, 'catalogue/tag_catalogue.html', {
756         'tags': tags,
757         'best': best,
758         'title': constants.CATEGORIES_NAME_PLURAL[category],
759         'whole_category': constants.WHOLE_CATEGORY[category],
760         'active_menu_item': 'theme' if category == 'theme' else None,
761     })
762
763
764 def collections(request):
765     objects = Collection.objects.all()
766
767     if len(objects) > 3:
768         best = random.sample(objects, 3)
769     else:
770         best = objects
771
772     return render(request, 'catalogue/collections.html', {
773         'objects': objects,
774         'best': best,
775     })