add limit options in reindex command (for debugging)
[wolnelektury.git] / src / catalogue / views.py
index a25a08f..267d9b4 100644 (file)
 #
 from collections import OrderedDict
 import re
 #
 from collections import OrderedDict
 import re
+import random
 
 from django.conf import settings
 from django.template import RequestContext
 from django.template.loader import render_to_string
 
 from django.conf import settings
 from django.template import RequestContext
 from django.template.loader import render_to_string
-from django.shortcuts import render_to_response, get_object_or_404, render
+from django.shortcuts import render_to_response, get_object_or_404, render, redirect
 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
 from django.core.urlresolvers import reverse
 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
 from django.core.urlresolvers import reverse
-from django.db.models import Q
+from django.db.models import Q, QuerySet
 from django.contrib.auth.decorators import login_required, user_passes_test
 from django.utils.http import urlquote_plus
 from django.utils import translation
 from django.utils.translation import ugettext as _, ugettext_lazy
 
 from ajaxable.utils import AjaxableFormView
 from django.contrib.auth.decorators import login_required, user_passes_test
 from django.utils.http import urlquote_plus
 from django.utils import translation
 from django.utils.translation import ugettext as _, ugettext_lazy
 
 from ajaxable.utils import AjaxableFormView
-from pdcounter import models as pdcounter_models
+from pdcounter.models import BookStub, Author
 from pdcounter import views as pdcounter_views
 from picture.models import Picture, PictureArea
 from pdcounter import views as pdcounter_views
 from picture.models import Picture, PictureArea
-from picture.views import picture_list_thumb
-from ssify import ssi_included, ssi_expect, SsiVariable as V
+from ssify import ssi_included, ssi_expect, SsiVariable as Var
 from suggest.forms import PublishingSuggestForm
 from suggest.forms import PublishingSuggestForm
+from catalogue import constants
 from catalogue import forms
 from catalogue.helpers import get_top_level_related_tags
 from catalogue import forms
 from catalogue.helpers import get_top_level_related_tags
-from catalogue import models
-from catalogue.utils import split_tags, MultiQuerySet, SortedMultiQuerySet
-from catalogue.templatetags.catalogue_tags import tag_list, collection_list
+from catalogue.models import Book, Collection, Tag, Fragment
+from catalogue.utils import split_tags
+from catalogue.models.tag import prefetch_relations
 
 staff_required = user_passes_test(lambda user: user.is_staff)
 
 
 
 staff_required = user_passes_test(lambda user: user.is_staff)
 
 
-def catalogue(request, as_json=False):
-    common_categories = ('author',)
-    split_categories = ('epoch', 'genre', 'kind')
-
-    categories = split_tags(
-        get_top_level_related_tags(categories=common_categories),
-        models.Tag.objects.usage_for_model(
-            models.Fragment, counts=True).filter(category='theme'),
-        models.Tag.objects.usage_for_model(
-            Picture, counts=True).filter(category__in=common_categories),
-        models.Tag.objects.usage_for_model(
-            PictureArea, counts=True).filter(
-            category='theme')
-    )
-    book_categories = split_tags(
-        get_top_level_related_tags(categories=split_categories)
-        )
-    picture_categories = split_tags(
-        models.Tag.objects.usage_for_model(
-            Picture, counts=True).filter(
-            category__in=split_categories),
-        )
-
-    collections = models.Collection.objects.all()
-
-    def render_tag_list(tags):
-        return render_to_string('catalogue/tag_list.html', tag_list(tags))
-
-    def render_split(with_books, with_pictures):
-        ctx = {}
-        if with_books:
-            ctx['books'] = render_tag_list(with_books)
-        if with_pictures:
-            ctx['pictures'] = render_tag_list(with_pictures)
-        return render_to_string('catalogue/tag_list_split.html', ctx)
-
-    output = {}
-    output['theme'] = render_tag_list(categories.get('theme', []))
-    for category in common_categories:
-        output[category] = render_tag_list(categories.get(category, []))
-    for category in split_categories:
-        output[category] = render_split(
-            book_categories.get(category, []),
-            picture_categories.get(category, []))
-
-    output['collections'] = render_to_string(
-        'catalogue/collection_list.html', collection_list(collections))
-    if as_json:
-        return JsonResponse(output)
-    else:
-        return render_to_response('catalogue/catalogue.html', locals(),
-            context_instance=RequestContext(request))
+def catalogue(request):
+    return render(request, 'catalogue/catalogue.html', {
+        'books': Book.objects.filter(parent=None),
+        'pictures': Picture.objects.all(),
+        'collections': Collection.objects.all(),
+        'active_menu_item': 'all_works',
+    })
 
 
 
 
-@ssi_included
-def catalogue_json(request):
-    return catalogue(request, True)
-
-
-def book_list(request, filter=None, get_filter=None,
-        template_name='catalogue/book_list.html',
-        nav_template_name='catalogue/snippets/book_list_nav.html',
-        list_template_name='catalogue/snippets/book_list.html',
-        context=None,
-        ):
-    """ generates a listing of all books, optionally filtered with a test function """
-    if get_filter:
-        filter = get_filter()
-    books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
+def book_list(request, filters=None, template_name='catalogue/book_list.html',
+              nav_template_name='catalogue/snippets/book_list_nav.html',
+              list_template_name='catalogue/snippets/book_list.html'):
+    """ generates a listing of all books, optionally filtered """
+    books_by_author, orphans, books_by_parent = Book.book_list(filters)
     books_nav = OrderedDict()
     for tag in books_by_author:
         if books_by_author[tag]:
             books_nav.setdefault(tag.sort_key[0], []).append(tag)
     books_nav = OrderedDict()
     for tag in books_by_author:
         if books_by_author[tag]:
             books_nav.setdefault(tag.sort_key[0], []).append(tag)
-    rendered_nav = render_to_string(nav_template_name, locals())
-    rendered_book_list = render_to_string(list_template_name, locals())
-    return render_to_response(template_name, locals(),
-        context_instance=RequestContext(request))
-
-
-def audiobook_list(request):
-    return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
-                     template_name='catalogue/audiobook_list.html',
-                     list_template_name='catalogue/snippets/audiobook_list.html',
-                     )
+    # WTF: dlaczego nie include?
+    return render_to_response(template_name, {
+        'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
+        'rendered_book_list': render_to_string(list_template_name, {
+            'books_by_author': books_by_author,
+            'orphans': orphans,
+            'books_by_parent': books_by_parent,
+        })
+    }, context_instance=RequestContext(request))
 
 
 def daisy_list(request):
 
 
 def daisy_list(request):
-    return book_list(request, Q(media__type='daisy'),
-                     template_name='catalogue/daisy_list.html',
-                     )
+    return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
 
 
 def collection(request, slug):
 
 
 def collection(request, slug):
-    coll = get_object_or_404(models.Collection, slug=slug)
-    if coll.kind == 'book':
-        view = book_list
-        tmpl = "catalogue/collection.html"
-    elif coll.kind == 'picture':
-        view = picture_list_thumb
-        tmpl = "picture/collection.html"
-    else:
-        raise ValueError('How do I show this kind of collection? %s' % coll.kind)
-    return view(request, get_filter=coll.get_query,
-                     template_name=tmpl,
-                     context={'collection': coll})
+    coll = get_object_or_404(Collection, slug=slug)
+    return render(request, 'catalogue/collection.html', {'collection': coll})
 
 
 def differentiate_tags(request, tags, ambiguous_slugs):
     beginning = '/'.join(tag.url_chunk for tag in tags)
     unparsed = '/'.join(ambiguous_slugs[1:])
     options = []
 
 
 def differentiate_tags(request, tags, ambiguous_slugs):
     beginning = '/'.join(tag.url_chunk for tag in tags)
     unparsed = '/'.join(ambiguous_slugs[1:])
     options = []
-    for tag in models.Tag.objects.filter(slug=ambiguous_slugs[0]):
+    for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
         options.append({
             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
             'tags': [tag]
         })
         options.append({
             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
             'tags': [tag]
         })
-    return render_to_response('catalogue/differentiate_tags.html',
-                {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
-                context_instance=RequestContext(request))
+    return render_to_response(
+        'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
+        context_instance=RequestContext(request))
+
+
+def object_list(request, objects, fragments=None, related_tags=None, tags=None, list_type='books', extra=None):
+    if not tags:
+        tags = []
+    tag_ids = [tag.pk for tag in tags]
+
+    related_tag_lists = []
+    if related_tags:
+        related_tag_lists.append(related_tags)
+    else:
+        related_tag_lists.append(
+            Tag.objects.usage_for_queryset(objects, counts=True).exclude(category='set').exclude(pk__in=tag_ids))
+    if not (extra and extra.get('theme_is_set')):
+        if fragments is None:
+            if list_type == 'gallery':
+                fragments = PictureArea.objects.filter(picture__in=objects)
+            else:
+                fragments = Fragment.objects.filter(book__in=objects)
+        related_tag_lists.append(
+            Tag.objects.usage_for_queryset(fragments, counts=True).filter(category='theme').exclude(pk__in=tag_ids)
+            .only('name', 'sort_key', 'category', 'slug'))
+        if isinstance(objects, QuerySet):
+            objects = prefetch_relations(objects, 'author')
+
+    categories = split_tags(*related_tag_lists)
+
+    objects = list(objects)
+
+    if not objects and len(tags) == 1 and list_type == 'books':
+        if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
+            return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
+
+    if len(objects) > 3:
+        best = random.sample(objects, 3)
+    else:
+        best = objects
+
+    result = {
+        'object_list': objects,
+        'categories': categories,
+        'list_type': list_type,
+        'tags': tags,
+
+        'formats_form': forms.DownloadFormatsForm(),
+        'best': best,
+        'active_menu_item': list_type,
+    }
+    if extra:
+        result.update(extra)
+    return render_to_response(
+        'catalogue/tagged_object_list.html', result,
+        context_instance=RequestContext(request))
+
+
+def literature(request):
+    books = Book.objects.filter(parent=None)
+
+    # last_published = Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:20]
+    # most_popular = Book.objects.exclude(cover_thumb='')\
+    #                    .order_by('-popularity__count', 'sort_key_author', 'sort_key')[:20]
+    return object_list(request, books, related_tags=get_top_level_related_tags([]))
+    # extra={
+    #     'last_published': last_published,
+    #     'most_popular': most_popular,
+    # })
+
+
+def gallery(request):
+    return object_list(request, Picture.objects.all(), list_type='gallery')
+
+
+def audiobooks(request):
+    audiobooks = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct()
+    return object_list(request, audiobooks, list_type='audiobooks', extra={
+        'daisy': Book.objects.filter(media__type='daisy').distinct(),
+    })
 
 
 
 
-# TODO: Rewrite this hellish piece of code which tries to do everything
-def tagged_object_list(request, tags=''):
-    # preliminary tests and conditions
+class ResponseInstead(Exception):
+    def __init__(self, response):
+        super(ResponseInstead, self).__init__()
+        self.response = response
+
+
+def analyse_tags(request, tag_str):
     try:
     try:
-        tags = models.Tag.get_tag_list(tags)
-    except models.Tag.DoesNotExist:
+        tags = Tag.get_tag_list(tag_str)
+    except Tag.DoesNotExist:
         # Perhaps the user is asking about an author in Public Domain
         # counter (they are not represented in tags)
         # Perhaps the user is asking about an author in Public Domain
         # counter (they are not represented in tags)
-        chunks = tags.split('/')
+        chunks = tag_str.split('/')
         if len(chunks) == 2 and chunks[0] == 'autor':
         if len(chunks) == 2 and chunks[0] == 'autor':
-            return pdcounter_views.author_detail(request, chunks[1])
+            raise ResponseInstead(pdcounter_views.author_detail(request, chunks[1]))
         else:
             raise Http404
         else:
             raise Http404
-    except models.Tag.MultipleObjectsReturned, e:
+    except Tag.MultipleObjectsReturned, e:
         # Ask the user to disambiguate
         # Ask the user to disambiguate
-        return differentiate_tags(request, e.tags, e.ambiguous_slugs)
-    except models.Tag.UrlDeprecationWarning, e:
-        return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
+        raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
+    except Tag.UrlDeprecationWarning, e:
+        raise ResponseInstead(HttpResponsePermanentRedirect(
+            reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
 
     try:
         if len(tags) > settings.MAX_TAG_LIST:
 
     try:
         if len(tags) > settings.MAX_TAG_LIST:
@@ -179,109 +193,100 @@ def tagged_object_list(request, tags=''):
     except AttributeError:
         pass
 
     except AttributeError:
         pass
 
-    # beginning of digestion
-    theme_is_set = [tag for tag in tags if tag.category == 'theme']
-    shelf_is_set = [tag for tag in tags if tag.category == 'set']
-    only_shelf = shelf_is_set and len(tags) == 1
-    only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
-    tags_pks = [tag.pk for tag in tags]
-
-    objects = None
-
-    if theme_is_set:
-        shelf_tags = [tag for tag in tags if tag.category == 'set']
-        fragment_tags = [tag for tag in tags if tag.category != 'set']
-        fragments = models.Fragment.tagged.with_all(fragment_tags)
-        areas = PictureArea.tagged.with_all(fragment_tags)
-
-        if shelf_tags:
-            books = models.Book.tagged.with_all(shelf_tags).order_by()
-            fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
-            areas = PictureArea.objects.none()
-
-        categories = split_tags(
-            models.Tag.objects.usage_for_queryset(fragments, counts=True
-                ).exclude(pk__in=tags_pks),
-            models.Tag.objects.usage_for_queryset(areas, counts=True
-                ).exclude(pk__in=tags_pks)
-            )
-
-        # we want the Pictures to go first
-        objects = MultiQuerySet(areas, fragments)
+    return tags
+
+
+def theme_list(request, tags, list_type):
+    shelf_tags = [tag for tag in tags if tag.category == 'set']
+    fragment_tags = [tag for tag in tags if tag.category != 'set']
+    if list_type == 'gallery':
+        fragments = PictureArea.tagged.with_all(fragment_tags)
     else:
     else:
-        all_books = models.Book.tagged.with_all(tags)
-        if shelf_is_set:
-            books = all_books.order_by('sort_key_author', 'title')
-            pictures = Picture.objects.none()
-            related_book_tags = models.Tag.objects.usage_for_queryset(
-                books, counts=True).exclude(
-                category='set').exclude(pk__in=tags_pks)
+        fragments = Fragment.tagged.with_all(fragment_tags)
+
+    if shelf_tags:
+        # TODO: Pictures on shelves not supported yet.
+        books = Book.tagged.with_all(shelf_tags).order_by()
+        fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
+
+    if not fragments and len(tags) == 1 and list_type == 'books':
+        if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
+            return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
+
+    return object_list(request, fragments, tags=tags, list_type=list_type, extra={
+        'theme_is_set': True,
+        'active_menu_item': 'theme',
+    })
+
+
+def tagged_object_list(request, tags, list_type):
+    try:
+        tags = analyse_tags(request, tags)
+    except ResponseInstead as e:
+        return e.response
+
+    if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
+        raise Http404
+
+    if any(tag.category in ('theme', 'thing') for tag in tags):
+        return theme_list(request, tags, list_type=list_type)
+
+    if list_type == 'books':
+        books = Book.tagged.with_all(tags)
+
+        if any(tag.category == 'set' for tag in tags):
+            params = {'objects': books}
         else:
         else:
-            books = models.Book.tagged_top_level(tags).order_by(
-                'sort_key_author', 'title')
-            pictures = Picture.tagged.with_all(tags).order_by(
-                'sort_key_author', 'title')
-            related_book_tags = get_top_level_related_tags(tags)
-
-        fragments = models.Fragment.objects.filter(book__in=all_books)
-        areas = PictureArea.objects.filter(picture__in=pictures)
-
-        categories = split_tags(
-            related_book_tags,
-            models.Tag.objects.usage_for_queryset(
-                pictures, counts=True).exclude(pk__in=tags_pks),
-            models.Tag.objects.usage_for_queryset(
-                fragments, counts=True).filter(
-                category='theme').exclude(pk__in=tags_pks),
-            models.Tag.objects.usage_for_queryset(
-                areas, counts=True).filter(
-                category__in=('theme', 'thing')).exclude(
-                pk__in=tags_pks),
-        )
-
-        objects = SortedMultiQuerySet(pictures, books,
-            order_by=('sort_key_author', 'title'))
-
-    return render_to_response('catalogue/tagged_object_list.html',
-        {
-            'object_list': objects,
-            'categories': categories,
-            'only_shelf': only_shelf,
-            'only_my_shelf': only_my_shelf,
-            'formats_form': forms.DownloadFormatsForm(),
-            'tags': tags,
-            'tag_ids': tags_pks,
-            'theme_is_set': theme_is_set,
-        },
-        context_instance=RequestContext(request))
+            params = {
+                'objects': Book.tagged_top_level(tags),
+                'fragments': Fragment.objects.filter(book__in=books),
+                'related_tags': get_top_level_related_tags(tags),
+            }
+    elif list_type == 'gallery':
+        params = {'objects': Picture.tagged.with_all(tags)}
+    elif list_type == 'audiobooks':
+        audiobooks = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct()
+        params = {
+            'objects': Book.tagged.with_all(tags, audiobooks),
+            'extra': {
+                'daisy': Book.tagged.with_all(tags, audiobooks.filter(media__type='daisy').distinct()),
+            }
+        }
+    else:
+        raise Http404
+
+    return object_list(request, tags=tags, list_type=list_type, **params)
 
 
 def book_fragments(request, slug, theme_slug):
 
 
 def book_fragments(request, slug, theme_slug):
-    book = get_object_or_404(models.Book, slug=slug)
-    theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
-    fragments = models.Fragment.tagged.with_all([theme]).filter(
+    book = get_object_or_404(Book, slug=slug)
+    theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
+    fragments = Fragment.tagged.with_all([theme]).filter(
         Q(book=book) | Q(book__ancestor=book))
 
         Q(book=book) | Q(book__ancestor=book))
 
-    return render_to_response('catalogue/book_fragments.html', locals(),
-        context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_fragments.html', {
+        'book': book,
+        'theme': theme,
+        'fragments': fragments,
+        'active_menu_item': 'books',
+    }, context_instance=RequestContext(request))
 
 
 def book_detail(request, slug):
     try:
 
 
 def book_detail(request, slug):
     try:
-        book = models.Book.objects.get(slug=slug)
-    except models.Book.DoesNotExist:
+        book = Book.objects.get(slug=slug)
+    except Book.DoesNotExist:
         return pdcounter_views.book_stub_detail(request, slug)
 
         return pdcounter_views.book_stub_detail(request, slug)
 
-    book_children = book.children.all().order_by('parent_number', 'sort_key')
-    return render_to_response('catalogue/book_detail.html', locals(),
-        context_instance=RequestContext(request))
-
+    return render_to_response('catalogue/book_detail.html', {
+        'book': book,
+        'tags': book.tags.exclude(category__in=('set', 'theme')),
+        'book_children': book.children.all().order_by('parent_number', 'sort_key'),
+        'active_menu_item': 'books',
+    }, context_instance=RequestContext(request))
 
 
-def player(request, slug):
-    book = get_object_or_404(models.Book, slug=slug)
-    if not book.has_media('mp3'):
-        raise Http404
 
 
+def get_audiobooks(book):
     ogg_files = {}
     for m in book.media.filter(type='ogg').order_by().iterator():
         ogg_files[m.name] = m
     ogg_files = {}
     for m in book.media.filter(type='ogg').order_by().iterator():
         ogg_files[m.name] = m
@@ -309,20 +314,31 @@ def player(request, slug):
         audiobooks.append(media)
 
     projects = sorted(projects)
         audiobooks.append(media)
 
     projects = sorted(projects)
+    return audiobooks, projects, have_oggs
 
 
-    extra_info = book.extra_info
 
 
-    return render_to_response('catalogue/player.html', locals(),
-        context_instance=RequestContext(request))
+# używane w publicznym interfejsie
+def player(request, slug):
+    book = get_object_or_404(Book, slug=slug)
+    if not book.has_media('mp3'):
+        raise Http404
+
+    audiobooks, projects, have_oggs = get_audiobooks(book)
+
+    return render_to_response('catalogue/player.html', {
+        'book': book,
+        'audiobook': '',
+        'audiobooks': audiobooks,
+        'projects': projects,
+    }, context_instance=RequestContext(request))
 
 
 def book_text(request, slug):
 
 
 def book_text(request, slug):
-    book = get_object_or_404(models.Book, slug=slug)
+    book = get_object_or_404(Book, slug=slug)
 
     if not book.has_html_file():
         raise Http404
 
     if not book.has_html_file():
         raise Http404
-    return render_to_response('catalogue/book_text.html', locals(),
-        context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_text.html', {'book': book}, context_instance=RequestContext(request))
 
 
 # ==========
 
 
 # ==========
@@ -334,17 +350,30 @@ def _no_diacritics_regexp(query):
 
     should be locale-aware """
     names = {
 
     should be locale-aware """
     names = {
-        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źżŹŻ',
-        u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
+        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źżŹŻ',
+        u'ą': u'ąĄ', u'ć': u'ćĆ', u'ę': u'ęĘ', u'ł': u'łŁ', u'ń': u'ńŃ', u'ó': u'óÓ', u'ś': u'śŚ', u'ź': u'źŹ',
+        u'ż': u'żŻ'
         }
         }
+
     def repl(m):
         l = m.group()
     def repl(m):
         l = m.group()
-        return u"(%s)" % '|'.join(names[l])
+        return u"(?:%s)" % '|'.join(names[l])
+
     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
 
     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
 
+
 def unicode_re_escape(query):
     """ Unicode-friendly version of re.escape """
 def unicode_re_escape(query):
     """ Unicode-friendly version of re.escape """
-    return re.sub(r'(?u)(\W)', r'\\\1', query)
+    s = list(query)
+    for i, c in enumerate(query):
+        if re.match(r'(?u)(\W)', c) and re.match(r'[\x00-\x7e]', c):
+            if c == "\000":
+                s[i] = "\\000"
+            else:
+                s[i] = "\\" + c
+    return query[:0].join(s)
+
 
 def _word_starts_with(name, prefix):
     """returns a Q object getting models having `name` contain a word
 
 def _word_starts_with(name, prefix):
     """returns a Q object getting models having `name` contain a word
@@ -375,8 +404,7 @@ def _sqlite_word_starts_with(name, prefix):
 
     SQLite in Django uses Python re module
     """
 
     SQLite in Django uses Python re module
     """
-    kwargs = {}
-    kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
+    kwargs = {'%s__iregex' % name: _word_starts_with_regexp(prefix)}
     return Q(**kwargs)
 
 
     return Q(**kwargs)
 
 
@@ -387,12 +415,13 @@ elif settings.DATABASE_ENGINE == 'sqlite3':
     _word_starts_with = _sqlite_word_starts_with
 
 
     _word_starts_with = _sqlite_word_starts_with
 
 
-class App():
+class App:
     def __init__(self, name, view):
         self.name = name
         self._view = view
         self.lower = name.lower()
         self.category = 'application'
     def __init__(self, name, view):
         self.name = name
         self._view = view
         self.lower = name.lower()
         self.category = 'application'
+
     def view(self):
         return reverse(*self._view)
 
     def view(self):
         return reverse(*self._view)
 
@@ -404,25 +433,25 @@ _apps = (
 def _tags_starting_with(prefix, user=None):
     prefix = prefix.lower()
     # PD counter
 def _tags_starting_with(prefix, user=None):
     prefix = prefix.lower()
     # PD counter
-    book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
-    authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
+    book_stubs = BookStub.objects.filter(_word_starts_with('title', prefix))
+    authors = Author.objects.filter(_word_starts_with('name', prefix))
 
 
-    books = models.Book.objects.filter(_word_starts_with('title', prefix))
-    tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
+    books = Book.objects.filter(_word_starts_with('title', prefix))
+    tags = Tag.objects.filter(_word_starts_with('name', prefix))
     if user and user.is_authenticated():
         tags = tags.filter(~Q(category='set') | Q(user=user))
     else:
         tags = tags.exclude(category='set')
 
     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
     if user and user.is_authenticated():
         tags = tags.filter(~Q(category='set') | Q(user=user))
     else:
         tags = tags.exclude(category='set')
 
     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
-    return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
+    return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + \
+        list(authors)
 
 
 def _get_result_link(match, tag_list):
 
 
 def _get_result_link(match, tag_list):
-    if isinstance(match, models.Tag):
+    if isinstance(match, Tag):
         return reverse('catalogue.views.tagged_object_list',
         return reverse('catalogue.views.tagged_object_list',
-            kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
-        )
+                       kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])})
     elif isinstance(match, App):
         return match.view()
     else:
     elif isinstance(match, App):
         return match.view()
     else:
@@ -430,7 +459,7 @@ def _get_result_link(match, tag_list):
 
 
 def _get_result_type(match):
 
 
 def _get_result_type(match):
-    if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
+    if isinstance(match, Book) or isinstance(match, BookStub):
         match_type = 'book'
     else:
         match_type = match.category
         match_type = 'book'
     else:
         match_type = match.category
@@ -439,11 +468,11 @@ def _get_result_type(match):
 
 def books_starting_with(prefix):
     prefix = prefix.lower()
 
 def books_starting_with(prefix):
     prefix = prefix.lower()
-    return models.Book.objects.filter(_word_starts_with('title', prefix))
+    return Book.objects.filter(_word_starts_with('title', prefix))
 
 
 def find_best_matches(query, user=None):
 
 
 def find_best_matches(query, user=None):
-    """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
+    """ Finds a Book, Tag, BookStub or Author best matching a query.
 
     Returns a with:
       - zero elements when nothing is found,
 
     Returns a with:
       - zero elements when nothing is found,
@@ -460,12 +489,12 @@ def find_best_matches(query, user=None):
     result = tuple(_tags_starting_with(query, user))
     # remove pdcounter stuff
     book_titles = set(match.pretty_title().lower() for match in result
     result = tuple(_tags_starting_with(query, user))
     # remove pdcounter stuff
     book_titles = set(match.pretty_title().lower() for match in result
-                      if isinstance(match, models.Book))
+                      if isinstance(match, Book))
     authors = set(match.name.lower() for match in result
     authors = set(match.name.lower() for match in result
-                  if isinstance(match, models.Tag) and match.category == 'author')
+                  if isinstance(match, Tag) and match.category == 'author')
     result = tuple(res for res in result if not (
     result = tuple(res for res in result if not (
-                 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
-                 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
+                 (isinstance(res, BookStub) and res.pretty_title().lower() in book_titles) or
+                 (isinstance(res, Author) and res.name.lower() in authors)
              ))
 
     exact_matches = tuple(res for res in result if res.name.lower() == query)
              ))
 
     exact_matches = tuple(res for res in result if res.name.lower() == query)
@@ -480,26 +509,32 @@ def search(request):
     prefix = request.GET.get('q', '')
 
     try:
     prefix = request.GET.get('q', '')
 
     try:
-        tag_list = models.Tag.get_tag_list(tags)
-    except:
+        tag_list = Tag.get_tag_list(tags)
+    except (Tag.DoesNotExist, Tag.MultipleObjectsReturned, Tag.UrlDeprecationWarning):
         tag_list = []
 
     try:
         result = find_best_matches(prefix, request.user)
     except ValueError:
         tag_list = []
 
     try:
         result = find_best_matches(prefix, request.user)
     except ValueError:
-        return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
+        return render_to_response(
+            'catalogue/search_too_short.html', {'tags': tag_list, 'prefix': prefix},
             context_instance=RequestContext(request))
 
     if len(result) == 1:
         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
     elif len(result) > 1:
             context_instance=RequestContext(request))
 
     if len(result) == 1:
         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
     elif len(result) > 1:
-        return render_to_response('catalogue/search_multiple_hits.html',
-            {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
+        return render_to_response(
+            'catalogue/search_multiple_hits.html',
+            {
+                'tags': tag_list, 'prefix': prefix,
+                'results': ((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)
+            },
             context_instance=RequestContext(request))
     else:
         form = PublishingSuggestForm(initial={"books": prefix + ", "})
             context_instance=RequestContext(request))
     else:
         form = PublishingSuggestForm(initial={"books": prefix + ", "})
-        return render_to_response('catalogue/search_no_hits.html',
-            {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
+        return render_to_response(
+            'catalogue/search_no_hits.html',
+            {'tags': tag_list, 'prefix': prefix, "pubsuggest_form": form},
             context_instance=RequestContext(request))
 
 
             context_instance=RequestContext(request))
 
 
@@ -511,11 +546,12 @@ def tags_starting_with(request):
     tags_list = []
     result = ""
     for tag in _tags_starting_with(prefix, request.user):
     tags_list = []
     result = ""
     for tag in _tags_starting_with(prefix, request.user):
-        if not tag.name in tags_list:
+        if tag.name not in tags_list:
             result += "\n" + tag.name
             tags_list.append(tag.name)
     return HttpResponse(result)
 
             result += "\n" + tag.name
             tags_list.append(tag.name)
     return HttpResponse(result)
 
+
 def json_tags_starting_with(request, callback=None):
     # Callback for JSONP
     prefix = request.GET.get('q', '')
 def json_tags_starting_with(request, callback=None):
     # Callback for JSONP
     prefix = request.GET.get('q', '')
@@ -525,7 +561,7 @@ def json_tags_starting_with(request, callback=None):
         return HttpResponse('')
     tags_list = []
     for tag in _tags_starting_with(prefix, request.user):
         return HttpResponse('')
     tags_list = []
     for tag in _tags_starting_with(prefix, request.user):
-        if not tag.name in tags_list:
+        if tag.name not in tags_list:
             tags_list.append(tag.name)
     if request.GET.get('mozhint', ''):
         result = [prefix, tags_list]
             tags_list.append(tag.name)
     if request.GET.get('mozhint', ''):
         result = [prefix, tags_list]
@@ -555,7 +591,9 @@ def import_book(request):
             info = sys.exc_info()
             exception = pprint.pformat(info[1])
             tb = '\n'.join(traceback.format_tb(info[2]))
             info = sys.exc_info()
             exception = pprint.pformat(info[1])
             tb = '\n'.join(traceback.format_tb(info[2]))
-            return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
+            return HttpResponse(
+                    _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
+                    mimetype='text/plain')
         return HttpResponse(_("Book imported successfully"))
     else:
         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
         return HttpResponse(_("Book imported successfully"))
     else:
         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
@@ -563,25 +601,23 @@ def import_book(request):
 
 # info views for API
 
 
 # info views for API
 
-def book_info(request, id, lang='pl'):
-    book = get_object_or_404(models.Book, id=id)
+def book_info(request, book_id, lang='pl'):
+    book = get_object_or_404(Book, id=book_id)
     # set language by hand
     translation.activate(lang)
     # set language by hand
     translation.activate(lang)
-    return render_to_response('catalogue/book_info.html', locals(),
-        context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_info.html', {'book': book}, context_instance=RequestContext(request))
 
 
 
 
-def tag_info(request, id):
-    tag = get_object_or_404(models.Tag, id=id)
+def tag_info(request, tag_id):
+    tag = get_object_or_404(Tag, id=tag_id)
     return HttpResponse(tag.description)
 
 
 def download_zip(request, format, slug=None):
     return HttpResponse(tag.description)
 
 
 def download_zip(request, format, slug=None):
-    url = None
-    if format in models.Book.ebook_formats:
-        url = models.Book.zip_format(format)
+    if format in Book.ebook_formats:
+        url = Book.zip_format(format)
     elif format in ('mp3', 'ogg') and slug is not None:
     elif format in ('mp3', 'ogg') and slug is not None:
-        book = get_object_or_404(models.Book, slug=slug)
+        book = get_object_or_404(Book, slug=slug)
         url = book.zip_audiobooks(format)
     else:
         raise Http404('No format specified for zip package')
         url = book.zip_audiobooks(format)
     else:
         raise Http404('No format specified for zip package')
@@ -592,6 +628,7 @@ class CustomPDFFormView(AjaxableFormView):
     form_class = forms.CustomPDFForm
     title = ugettext_lazy('Download custom PDF')
     submit = ugettext_lazy('Download')
     form_class = forms.CustomPDFForm
     title = ugettext_lazy('Download custom PDF')
     submit = ugettext_lazy('Download')
+    template = 'catalogue/custom_pdf_form.html'
     honeypot = True
 
     def __call__(self, *args, **kwargs):
     honeypot = True
 
     def __call__(self, *args, **kwargs):
@@ -604,7 +641,7 @@ class CustomPDFFormView(AjaxableFormView):
         return (obj,), {}
 
     def get_object(self, request, slug, *args, **kwargs):
         return (obj,), {}
 
     def get_object(self, request, slug, *args, **kwargs):
-        return get_object_or_404(models.Book, slug=slug)
+        return get_object_or_404(Book, slug=slug)
 
     def context_description(self, request, obj):
         return obj.pretty_title()
 
     def context_description(self, request, obj):
         return obj.pretty_title()
@@ -617,14 +654,14 @@ class CustomPDFFormView(AjaxableFormView):
 
 @ssi_included
 def book_mini(request, pk, with_link=True):
 
 @ssi_included
 def book_mini(request, pk, with_link=True):
-    book = get_object_or_404(models.Book, pk=pk)
-    author_str = ", ".join(tag.name
-        for tag in book.tags.filter(category='author'))
+    # book = get_object_or_404(Book, pk=pk)
+    try:
+        book = Book.objects.only('cover_thumb', 'title', 'language', 'slug').get(pk=pk)
+    except Book.DoesNotExist:
+        raise Http404
     return render(request, 'catalogue/book_mini_box.html', {
         'book': book,
     return render(request, 'catalogue/book_mini_box.html', {
         'book': book,
-        'author_str': author_str,
-        'with_link': with_link,
-        'show_lang': book.language_code() != settings.LANGUAGE_CODE,
+        'no_link': not with_link,
     })
 
 
     })
 
 
@@ -634,8 +671,9 @@ def book_mini(request, pk, with_link=True):
         ('social_tags.book_shelf_tags', (ipk,)),
     ))(ssi_expect(pk, int)))
 def book_short(request, pk):
         ('social_tags.book_shelf_tags', (ipk,)),
     ))(ssi_expect(pk, int)))
 def book_short(request, pk):
-    book = get_object_or_404(models.Book, pk=pk)
+    book = get_object_or_404(Book, pk=pk)
     stage_note, stage_note_url = book.stage_note()
     stage_note, stage_note_url = book.stage_note()
+    audiobooks, projects, have_oggs = get_audiobooks(book)
 
     return render(request, 'catalogue/book_short.html', {
         'book': book,
 
     return render(request, 'catalogue/book_short.html', {
         'book': book,
@@ -646,19 +684,23 @@ def book_short(request, pk):
         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
         'stage_note': stage_note,
         'stage_note_url': stage_note_url,
         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
         'stage_note': stage_note,
         'stage_note_url': stage_note_url,
+        'audiobooks': audiobooks,
+        'have_oggs': have_oggs,
     })
 
 
     })
 
 
-@ssi_included(get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
+@ssi_included(
+    get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
     (lambda ipk: (
         ('social_tags.choose_cite', [ipk]),
         ('catalogue_tags.choose_fragment', [ipk], {
     (lambda ipk: (
         ('social_tags.choose_cite', [ipk]),
         ('catalogue_tags.choose_fragment', [ipk], {
-            'unless': V('social_tags.choose_cite', [ipk])}),
+            'unless': Var('social_tags.choose_cite', [ipk])}),
     ))(ssi_expect(pk, int)))
 def book_wide(request, pk):
     ))(ssi_expect(pk, int)))
 def book_wide(request, pk):
-    book = get_object_or_404(models.Book, pk=pk)
+    book = get_object_or_404(Book, pk=pk)
     stage_note, stage_note_url = book.stage_note()
     extra_info = book.extra_info
     stage_note, stage_note_url = book.stage_note()
     extra_info = book.extra_info
+    audiobooks, projects, have_oggs = get_audiobooks(book)
 
     return render(request, 'catalogue/book_wide.html', {
         'book': book,
 
     return render(request, 'catalogue/book_wide.html', {
         'book': book,
@@ -672,20 +714,88 @@ def book_wide(request, pk):
         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
         'extra_info': extra_info,
         'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
         'extra_info': extra_info,
         'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
-        'themes': book.related_themes(),
+        'audiobooks': audiobooks,
+        'have_oggs': have_oggs,
     })
 
 
 @ssi_included
 def fragment_short(request, pk):
     })
 
 
 @ssi_included
 def fragment_short(request, pk):
-    fragment = get_object_or_404(models.Fragment, pk=pk)
-    return render(request, 'catalogue/fragment_short.html',
-        {'fragment': fragment})
+    fragment = get_object_or_404(Fragment, pk=pk)
+    return render(request, 'catalogue/fragment_short.html', {'fragment': fragment})
 
 
 @ssi_included
 def fragment_promo(request, pk):
 
 
 @ssi_included
 def fragment_promo(request, pk):
-    fragment = get_object_or_404(models.Fragment, pk=pk)
-    return render(request, 'catalogue/fragment_promo.html', {
-        'fragment': fragment
+    fragment = get_object_or_404(Fragment, pk=pk)
+    return render(request, 'catalogue/fragment_promo.html', {'fragment': fragment})
+
+
+@ssi_included
+def tag_box(request, pk):
+    tag = get_object_or_404(Tag, pk=pk)
+    assert tag.category != 'set'
+
+    return render(request, 'catalogue/tag_box.html', {
+        'tag': tag,
+    })
+
+
+@ssi_included
+def collection_box(request, pk):
+    collection = get_object_or_404(Collection, pk=pk)
+
+    return render(request, 'catalogue/collection_box.html', {
+        'collection': collection,
     })
     })
+
+
+def tag_catalogue(request, category):
+    if category == 'theme':
+        tags = Tag.objects.usage_for_model(
+            Fragment, counts=True).filter(category='theme')
+    else:
+        tags = list(get_top_level_related_tags((), categories=(category,)))
+
+    described_tags = [tag for tag in tags if tag.description]
+
+    if len(described_tags) > 4:
+        best = random.sample(described_tags, 4)
+    else:
+        best = described_tags
+
+    return render(request, 'catalogue/tag_catalogue.html', {
+        'tags': tags,
+        'best': best,
+        'title': constants.CATEGORIES_NAME_PLURAL[category],
+        'whole_category': constants.WHOLE_CATEGORY[category],
+        'active_menu_item': 'theme' if category == 'theme' else None,
+    })
+
+
+def collections(request):
+    objects = Collection.objects.all()
+
+    if len(objects) > 3:
+        best = random.sample(objects, 3)
+    else:
+        best = objects
+
+    return render(request, 'catalogue/collections.html', {
+        'objects': objects,
+        'best': best,
+    })
+
+
+def ridero_cover(request, slug):
+    from librarian.cover import make_cover
+    wldoc = Book.objects.get(slug=slug).wldocument()
+    cover = make_cover(wldoc.book_info, width=980, bleed=20, format='PNG')
+    response = HttpResponse(content_type="image/png")
+    cover.save(response)
+    return response
+
+
+def get_isbn(request, book_format, slug):
+    book = Book.objects.get(slug=slug)
+    return HttpResponse(book.extra_info.get('isbn_%s' % book_format))