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