View for list of catalogs
[wolnelektury.git] / apps / 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 import re
6 import itertools
7
8 from django.conf import settings
9 from django.core.cache import get_cache
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, redirect
13 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
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.datastructures import SortedDict
18 from django.utils.http import urlquote_plus
19 from django.utils import translation
20 from django.utils.translation import ugettext as _, ugettext_lazy
21 from django.views.decorators.cache import never_cache
22 from django.views.decorators.vary import vary_on_headers
23
24 from ajaxable.utils import JSONResponse, AjaxableFormView
25 from catalogue import models
26 from catalogue import forms
27 from catalogue.utils import split_tags, MultiQuerySet
28 from catalogue.templatetags.catalogue_tags import tag_list, collection_list
29 from pdcounter import models as pdcounter_models
30 from pdcounter import views as pdcounter_views
31 from suggest.forms import PublishingSuggestForm
32 from picture.models import Picture
33
34 staff_required = user_passes_test(lambda user: user.is_staff)
35 permanent_cache = get_cache('permanent')
36
37
38 @vary_on_headers('X-Requested-With')
39 def catalogue(request):
40     tags = models.Tag.objects.exclude(
41         category__in=('set', 'book')).exclude(book_count=0)
42     tags = list(tags)
43     for tag in tags:
44         tag.count = tag.book_count
45     categories = split_tags(tags)
46     fragment_tags = categories.get('theme', [])
47     collections = models.Collection.objects.all()
48
49     if request.is_ajax():
50         render_tag_list = lambda x: render_to_string(
51             'catalogue/tag_list.html', tag_list(x))
52         output = {'theme': render_tag_list(fragment_tags)}
53         for category, tags in categories.items():
54             output[category] = render_tag_list(tags)
55         output['collections'] = render_to_string(
56             'catalogue/collection_list.html', collection_list(collections))
57         return JSONResponse(output)
58     else:
59         return render_to_response('catalogue/catalogue.html', locals(),
60             context_instance=RequestContext(request))
61
62
63 def book_list(request, filter=None, template_name='catalogue/book_list.html',
64         nav_template_name='catalogue/snippets/book_list_nav.html',
65         list_template_name='catalogue/snippets/book_list.html',
66         cache_key='catalogue.book_list',
67         context=None,
68         ):
69     """ generates a listing of all books, optionally filtered with a test function """
70     cached = permanent_cache.get(cache_key)
71     if cached is not None:
72         rendered_nav, rendered_book_list = cached
73     else:
74         books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
75         books_nav = SortedDict()
76         for tag in books_by_author:
77             if books_by_author[tag]:
78                 books_nav.setdefault(tag.sort_key[0], []).append(tag)
79         rendered_nav = render_to_string(nav_template_name, locals())
80         rendered_book_list = render_to_string(list_template_name, locals())
81         permanent_cache.set(cache_key, (rendered_nav, rendered_book_list))
82     return render_to_response(template_name, locals(),
83         context_instance=RequestContext(request))
84
85
86 def audiobook_list(request):
87     return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
88                      template_name='catalogue/audiobook_list.html',
89                      list_template_name='catalogue/snippets/audiobook_list.html',
90                      cache_key='catalogue.audiobook_list')
91
92
93 def daisy_list(request):
94     return book_list(request, Q(media__type='daisy'),
95                      template_name='catalogue/daisy_list.html',
96                      cache_key='catalogue.daisy_list')
97
98
99 def collection(request, slug):
100     coll = get_object_or_404(models.Collection, slug=slug)
101     slugs = coll.book_slugs.split()
102     # allow URIs
103     slugs = [slug.rstrip('/').rsplit('/', 1)[-1] if '/' in slug else slug
104                 for slug in slugs]
105     return book_list(request, Q(slug__in=slugs),
106                      template_name='catalogue/collection.html',
107                      cache_key='catalogue.collection:%s' % coll.slug,
108                      context={'collection': coll})
109
110
111 def differentiate_tags(request, tags, ambiguous_slugs):
112     beginning = '/'.join(tag.url_chunk for tag in tags)
113     unparsed = '/'.join(ambiguous_slugs[1:])
114     options = []
115     for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
116         options.append({
117             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
118             'tags': [tag]
119         })
120     return render_to_response('catalogue/differentiate_tags.html',
121                 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
122                 context_instance=RequestContext(request))
123
124
125 @never_cache
126 def tagged_object_list(request, tags=''):
127     try:
128         tags = models.Tag.get_tag_list(tags)
129     except models.Tag.DoesNotExist:
130         chunks = tags.split('/')
131         if len(chunks) == 2 and chunks[0] == 'autor':
132             return pdcounter_views.author_detail(request, chunks[1])
133         else:
134             raise Http404
135     except models.Tag.MultipleObjectsReturned, e:
136         return differentiate_tags(request, e.tags, e.ambiguous_slugs)
137     except models.Tag.UrlDeprecationWarning, e:
138         return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
139
140     try:
141         if len(tags) > settings.MAX_TAG_LIST:
142             raise Http404
143     except AttributeError:
144         pass
145
146     if len([tag for tag in tags if tag.category == 'book']):
147         raise Http404
148
149     theme_is_set = [tag for tag in tags if tag.category == 'theme']
150     shelf_is_set = [tag for tag in tags if tag.category == 'set']
151     only_shelf = shelf_is_set and len(tags) == 1
152     only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
153
154     objects = only_author = None
155     categories = {}
156
157     if theme_is_set:
158         shelf_tags = [tag for tag in tags if tag.category == 'set']
159         fragment_tags = [tag for tag in tags if tag.category != 'set']
160         fragments = models.Fragment.tagged.with_all(fragment_tags)
161
162         if shelf_tags:
163             books = models.Book.tagged.with_all(shelf_tags).order_by()
164             l_tags = models.Tag.objects.filter(category='book',
165                 slug__in=[book.book_tag_slug() for book in books.iterator()])
166             fragments = models.Fragment.tagged.with_any(l_tags, fragments)
167
168         # newtagging goes crazy if we just try:
169         #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
170         #                    extra={'where': ["catalogue_tag.category != 'book'"]})
171         fragment_keys = [fragment.pk for fragment in fragments.iterator()]
172         if fragment_keys:
173             related_tags = models.Fragment.tags.usage(counts=True,
174                                 filters={'pk__in': fragment_keys},
175                                 extra={'where': ["catalogue_tag.category != 'book'"]})
176             related_tags = (tag for tag in related_tags if tag not in fragment_tags)
177             categories = split_tags(related_tags)
178
179             objects = fragments
180     else:
181         if shelf_is_set:
182             objects = models.Book.tagged.with_all(tags)
183         else:
184             objects = models.Book.tagged_top_level(tags)
185
186         # get related tags from `tag_counter` and `theme_counter`
187         related_counts = {}
188         tags_pks = [tag.pk for tag in tags]
189         for book in objects.iterator():
190             for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
191                 if tag_pk in tags_pks:
192                     continue
193                 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
194         related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
195         related_tags = [tag for tag in related_tags if tag not in tags]
196         for tag in related_tags:
197             tag.count = related_counts[tag.pk]
198
199         categories = split_tags(related_tags)
200         del related_tags
201
202     if not objects:
203         only_author = len(tags) == 1 and tags[0].category == 'author'
204         objects = models.Book.objects.none()
205
206     # Add pictures
207     objects = MultiQuerySet(Picture.tagged.with_all(tags), objects)
208
209     return render_to_response('catalogue/tagged_object_list.html',
210         {
211             'object_list': objects,
212             'categories': categories,
213             'only_shelf': only_shelf,
214             'only_author': only_author,
215             'only_my_shelf': only_my_shelf,
216             'formats_form': forms.DownloadFormatsForm(),
217             'tags': tags,
218             'theme_is_set': theme_is_set,
219         },
220         context_instance=RequestContext(request))
221
222
223 def book_fragments(request, slug, theme_slug):
224     book = get_object_or_404(models.Book, slug=slug)
225
226     book_tag = book.book_tag()
227     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
228     fragments = models.Fragment.tagged.with_all([book_tag, theme])
229
230     return render_to_response('catalogue/book_fragments.html', locals(),
231         context_instance=RequestContext(request))
232
233
234 @never_cache
235 def book_detail(request, slug):
236     try:
237         book = models.Book.objects.get(slug=slug)
238     except models.Book.DoesNotExist:
239         return pdcounter_views.book_stub_detail(request, slug)
240
241     book_children = book.children.all().order_by('parent_number', 'sort_key')
242     return render_to_response('catalogue/book_detail.html', locals(),
243         context_instance=RequestContext(request))
244
245
246 def player(request, slug):
247     book = get_object_or_404(models.Book, slug=slug)
248     if not book.has_media('mp3'):
249         raise Http404
250
251     ogg_files = {}
252     for m in book.media.filter(type='ogg').order_by().iterator():
253         ogg_files[m.name] = m
254
255     audiobooks = []
256     have_oggs = True
257     projects = set()
258     for mp3 in book.media.filter(type='mp3').iterator():
259         # ogg files are always from the same project
260         meta = mp3.extra_info
261         project = meta.get('project')
262         if not project:
263             # temporary fallback
264             project = u'CzytamySłuchając'
265
266         projects.add((project, meta.get('funded_by', '')))
267
268         media = {'mp3': mp3}
269
270         ogg = ogg_files.get(mp3.name)
271         if ogg:
272             media['ogg'] = ogg
273         else:
274             have_oggs = False
275         audiobooks.append(media)
276
277     projects = sorted(projects)
278
279     extra_info = book.extra_info
280
281     return render_to_response('catalogue/player.html', locals(),
282         context_instance=RequestContext(request))
283
284
285 def book_text(request, slug):
286     book = get_object_or_404(models.Book, slug=slug)
287
288     if not book.has_html_file():
289         raise Http404
290     book_themes = {}
291     for fragment in book.fragments.all().iterator():
292         for theme in fragment.tags.filter(category='theme').iterator():
293             book_themes.setdefault(theme, []).append(fragment)
294
295     book_themes = book_themes.items()
296     book_themes.sort(key=lambda s: s[0].sort_key)
297     related = book.related_info()
298     return render_to_response('catalogue/book_text.html', locals(),
299         context_instance=RequestContext(request))
300
301
302 # ==========
303 # = Search =
304 # ==========
305
306 def _no_diacritics_regexp(query):
307     """ returns a regexp for searching for a query without diacritics
308
309     should be locale-aware """
310     names = {
311         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źżŹŻ',
312         u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
313         }
314     def repl(m):
315         l = m.group()
316         return u"(%s)" % '|'.join(names[l])
317     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
318
319 def unicode_re_escape(query):
320     """ Unicode-friendly version of re.escape """
321     return re.sub('(?u)(\W)', r'\\\1', query)
322
323 def _word_starts_with(name, prefix):
324     """returns a Q object getting models having `name` contain a word
325     starting with `prefix`
326
327     We define word characters as alphanumeric and underscore, like in JS.
328
329     Works for MySQL, PostgreSQL, Oracle.
330     For SQLite, _sqlite* version is substituted for this.
331     """
332     kwargs = {}
333
334     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
335     # can't use [[:<:]] (word start),
336     # but we want both `xy` and `(xy` to catch `(xyz)`
337     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
338
339     return Q(**kwargs)
340
341
342 def _word_starts_with_regexp(prefix):
343     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
344     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
345
346
347 def _sqlite_word_starts_with(name, prefix):
348     """ version of _word_starts_with for SQLite
349
350     SQLite in Django uses Python re module
351     """
352     kwargs = {}
353     kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
354     return Q(**kwargs)
355
356
357 if hasattr(settings, 'DATABASES'):
358     if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
359         _word_starts_with = _sqlite_word_starts_with
360 elif settings.DATABASE_ENGINE == 'sqlite3':
361     _word_starts_with = _sqlite_word_starts_with
362
363
364 class App():
365     def __init__(self, name, view):
366         self.name = name
367         self._view = view
368         self.lower = name.lower()
369         self.category = 'application'
370     def view(self):
371         return reverse(*self._view)
372
373 _apps = (
374     App(u'Leśmianator', (u'lesmianator', )),
375     )
376
377
378 def _tags_starting_with(prefix, user=None):
379     prefix = prefix.lower()
380     # PD counter
381     book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
382     authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
383
384     books = models.Book.objects.filter(_word_starts_with('title', prefix))
385     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
386     if user and user.is_authenticated():
387         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
388     else:
389         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
390
391     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
392     return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
393
394
395 def _get_result_link(match, tag_list):
396     if isinstance(match, models.Tag):
397         return reverse('catalogue.views.tagged_object_list',
398             kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
399         )
400     elif isinstance(match, App):
401         return match.view()
402     else:
403         return match.get_absolute_url()
404
405
406 def _get_result_type(match):
407     if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
408         type = 'book'
409     else:
410         type = match.category
411     return type
412
413
414 def books_starting_with(prefix):
415     prefix = prefix.lower()
416     return models.Book.objects.filter(_word_starts_with('title', prefix))
417
418
419 def find_best_matches(query, user=None):
420     """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
421
422     Returns a with:
423       - zero elements when nothing is found,
424       - one element when a best result is found,
425       - more then one element on multiple exact matches
426
427     Raises a ValueError on too short a query.
428     """
429
430     query = query.lower()
431     if len(query) < 2:
432         raise ValueError("query must have at least two characters")
433
434     result = tuple(_tags_starting_with(query, user))
435     # remove pdcounter stuff
436     book_titles = set(match.pretty_title().lower() for match in result
437                       if isinstance(match, models.Book))
438     authors = set(match.name.lower() for match in result
439                   if isinstance(match, models.Tag) and match.category=='author')
440     result = tuple(res for res in result if not (
441                  (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
442                  or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
443              ))
444
445     exact_matches = tuple(res for res in result if res.name.lower() == query)
446     if exact_matches:
447         return exact_matches
448     else:
449         return tuple(result)[:1]
450
451
452 def search(request):
453     tags = request.GET.get('tags', '')
454     prefix = request.GET.get('q', '')
455
456     try:
457         tag_list = models.Tag.get_tag_list(tags)
458     except:
459         tag_list = []
460
461     try:
462         result = find_best_matches(prefix, request.user)
463     except ValueError:
464         return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
465             context_instance=RequestContext(request))
466
467     if len(result) == 1:
468         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
469     elif len(result) > 1:
470         return render_to_response('catalogue/search_multiple_hits.html',
471             {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
472             context_instance=RequestContext(request))
473     else:
474         form = PublishingSuggestForm(initial={"books": prefix + ", "})
475         return render_to_response('catalogue/search_no_hits.html',
476             {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
477             context_instance=RequestContext(request))
478
479
480 def tags_starting_with(request):
481     prefix = request.GET.get('q', '')
482     # Prefix must have at least 2 characters
483     if len(prefix) < 2:
484         return HttpResponse('')
485     tags_list = []
486     result = ""
487     for tag in _tags_starting_with(prefix, request.user):
488         if not tag.name in tags_list:
489             result += "\n" + tag.name
490             tags_list.append(tag.name)
491     return HttpResponse(result)
492
493 def json_tags_starting_with(request, callback=None):
494     # Callback for JSONP
495     prefix = request.GET.get('q', '')
496     callback = request.GET.get('callback', '')
497     # Prefix must have at least 2 characters
498     if len(prefix) < 2:
499         return HttpResponse('')
500     tags_list = []
501     for tag in _tags_starting_with(prefix, request.user):
502         if not tag.name in tags_list:
503             tags_list.append(tag.name)
504     if request.GET.get('mozhint', ''):
505         result = [prefix, tags_list]
506     else:
507         result = {"matches": tags_list}
508     return JSONResponse(result, callback)
509
510
511 # =========
512 # = Admin =
513 # =========
514 @login_required
515 @staff_required
516 def import_book(request):
517     """docstring for import_book"""
518     book_import_form = forms.BookImportForm(request.POST, request.FILES)
519     if book_import_form.is_valid():
520         try:
521             book_import_form.save()
522         except:
523             import sys
524             import pprint
525             import traceback
526             info = sys.exc_info()
527             exception = pprint.pformat(info[1])
528             tb = '\n'.join(traceback.format_tb(info[2]))
529             return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
530         return HttpResponse(_("Book imported successfully"))
531     else:
532         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
533
534
535 # info views for API
536
537 def book_info(request, id, lang='pl'):
538     book = get_object_or_404(models.Book, id=id)
539     # set language by hand
540     translation.activate(lang)
541     return render_to_response('catalogue/book_info.html', locals(),
542         context_instance=RequestContext(request))
543
544
545 def tag_info(request, id):
546     tag = get_object_or_404(models.Tag, id=id)
547     return HttpResponse(tag.description)
548
549
550 def download_zip(request, format, slug=None):
551     url = None
552     if format in models.Book.ebook_formats:
553         url = models.Book.zip_format(format)
554     elif format in ('mp3', 'ogg') and slug is not None:
555         book = get_object_or_404(models.Book, slug=slug)
556         url = book.zip_audiobooks(format)
557     else:
558         raise Http404('No format specified for zip package')
559     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
560
561
562 class CustomPDFFormView(AjaxableFormView):
563     form_class = forms.CustomPDFForm
564     title = ugettext_lazy('Download custom PDF')
565     submit = ugettext_lazy('Download')
566     honeypot = True
567
568     def __call__(self, *args, **kwargs):
569         if settings.NO_CUSTOM_PDF:
570             raise Http404('Custom PDF is disabled')
571         return super(CustomPDFFormView, self).__call__(*args, **kwargs)
572
573     def form_args(self, request, obj):
574         """Override to parse view args and give additional args to the form."""
575         return (obj,), {}
576
577     def get_object(self, request, slug, *args, **kwargs):
578         return get_object_or_404(models.Book, slug=slug)
579
580     def context_description(self, request, obj):
581         return obj.pretty_title()