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