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