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