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