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