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