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