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