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