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