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