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