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