tag description effects (#682)
[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 tempfile
6 import zipfile
7 import sys
8 import pprint
9 import traceback
10 import re
11 import itertools
12 from operator import itemgetter 
13
14 from django.conf import settings
15 from django.template import RequestContext
16 from django.shortcuts import render_to_response, get_object_or_404
17 from django.http import HttpResponse, HttpResponseRedirect, Http404
18 from django.core.urlresolvers import reverse
19 from django.db.models import Q
20 from django.contrib.auth.decorators import login_required, user_passes_test
21 from django.utils.datastructures import SortedDict
22 from django.views.decorators.http import require_POST
23 from django.contrib import auth
24 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
25 from django.utils import simplejson
26 from django.utils.functional import Promise
27 from django.utils.encoding import force_unicode
28 from django.utils.http import urlquote_plus
29 from django.views.decorators import cache
30 from django.utils.translation import ugettext as _
31 from django.views.generic.list_detail import object_list
32
33 from catalogue import models
34 from catalogue import forms
35 from catalogue.utils import split_tags
36 from newtagging import views as newtagging_views
37
38
39 staff_required = user_passes_test(lambda user: user.is_staff)
40
41
42 class LazyEncoder(simplejson.JSONEncoder):
43     def default(self, obj):
44         if isinstance(obj, Promise):
45             return force_unicode(obj)
46         return obj
47
48
49 def main_page(request):
50     if request.user.is_authenticated():
51         shelves = models.Tag.objects.filter(category='set', user=request.user)
52         new_set_form = forms.NewSetForm()
53     extra_where = "NOT catalogue_tag.category = 'set'"
54     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
55     fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
56         extra={'where': ["catalogue_tag.category = 'theme'"] + [extra_where]})
57     categories = split_tags(tags)
58
59     form = forms.SearchForm()
60     return render_to_response('catalogue/main_page.html', locals(),
61         context_instance=RequestContext(request))
62
63
64 def book_list(request):
65     books = models.Book.objects.all()
66     form = forms.SearchForm()
67
68     books_by_first_letter = SortedDict()
69     for book in books:
70         books_by_first_letter.setdefault(book.title[0], []).append(book)
71
72     return render_to_response('catalogue/book_list.html', locals(),
73         context_instance=RequestContext(request))
74
75
76 def differentiate_tags(request, tags, ambiguous_slugs):
77     beginning = '/'.join(tag.url_chunk for tag in tags)
78     unparsed = '/'.join(ambiguous_slugs[1:])
79     options = []
80     for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
81         options.append({
82             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
83             'tags': [tag]
84         })
85     return render_to_response('catalogue/differentiate_tags.html',
86                 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}, 
87                 context_instance=RequestContext(request))
88
89
90 def tagged_object_list(request, tags=''):
91     try:
92         tags = models.Tag.get_tag_list(tags)
93     except models.Tag.DoesNotExist:
94         raise Http404
95     except models.Tag.MultipleObjectsReturned, e:
96         return differentiate_tags(request, e.tags, e.ambiguous_slugs)
97
98     try:
99         if len(tags) > settings.MAX_TAG_LIST:
100             raise Http404
101     except AttributeError:
102         pass
103
104     if len([tag for tag in tags if tag.category == 'book']):
105         raise Http404
106
107     theme_is_set = [tag for tag in tags if tag.category == 'theme']
108     shelf_is_set = len(tags) == 1 and tags[0].category == 'set'
109     my_shelf_is_set = shelf_is_set and request.user.is_authenticated() and request.user == tags[0].user
110
111     objects = only_author = pd_counter = None
112     categories = {}
113
114     if theme_is_set:
115         shelf_tags = [tag for tag in tags if tag.category == 'set']
116         fragment_tags = [tag for tag in tags if tag.category != 'set']
117         fragments = models.Fragment.tagged.with_all(fragment_tags)
118
119         if shelf_tags:
120             books = models.Book.tagged.with_all(shelf_tags).order_by()
121             l_tags = [book.book_tag() for book in books]
122             fragments = models.Fragment.tagged.with_any(l_tags, fragments)
123
124         # newtagging goes crazy if we just try:
125         #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True, 
126         #                    extra={'where': ["catalogue_tag.category != 'book'"]})
127         fragment_keys = [fragment.pk for fragment in fragments]
128         if fragment_keys:
129             related_tags = models.Fragment.tags.usage(counts=True,
130                                 filters={'pk__in': fragment_keys},
131                                 extra={'where': ["catalogue_tag.category != 'book'"]})
132             related_tags = (tag for tag in related_tags if tag not in fragment_tags)
133             categories = split_tags(related_tags)
134
135             objects = fragments
136     else:
137         # get relevant books and their tags
138         objects = models.Book.tagged.with_all(tags).order_by()
139         l_tags = [book.book_tag() for book in objects]
140         # eliminate descendants
141         descendants_keys = [book.pk for book in models.Book.tagged.with_any(l_tags)]
142         if descendants_keys:
143             objects = objects.exclude(pk__in=descendants_keys)
144         
145         # get related tags from `tag_counter` and `theme_counter`
146         related_counts = {}
147         tags_pks = [tag.pk for tag in tags]
148         for book in objects:
149             for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
150                 if tag_pk in tags_pks:
151                     continue
152                 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
153         related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
154         related_tags = [tag for tag in related_tags if tag not in tags]
155         for tag in related_tags:
156             tag.count = related_counts[tag.pk]
157         
158         categories = split_tags(related_tags)
159         del related_tags
160
161     if not objects:
162         only_author = len(tags) == 1 and tags[0].category == 'author'
163         pd_counter = only_author and tags[0].goes_to_pd()
164         objects = models.Book.objects.none()
165
166     return object_list(
167         request,
168         objects,
169         template_name='catalogue/tagged_object_list.html',
170         extra_context={
171             'categories': categories,
172             'shelf_is_set': shelf_is_set,
173             'only_author': only_author,
174             'pd_counter': pd_counter,
175             'user_is_owner': my_shelf_is_set,
176             'formats_form': forms.DownloadFormatsForm(),
177
178             'tags': tags,
179         }
180     )
181
182
183 def book_fragments(request, book_slug, theme_slug):
184     book = get_object_or_404(models.Book, slug=book_slug)
185     book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
186     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
187     fragments = models.Fragment.tagged.with_all([book_tag, theme])
188
189     form = forms.SearchForm()
190     return render_to_response('catalogue/book_fragments.html', locals(),
191         context_instance=RequestContext(request))
192
193
194 def book_detail(request, slug):
195     try:
196         book = models.Book.objects.get(slug=slug)
197     except models.Book.DoesNotExist:
198         return book_stub_detail(request, slug)
199
200     book_tag = book.book_tag()
201     tags = list(book.tags.filter(~Q(category='set')))
202     categories = split_tags(tags)
203     book_children = book.children.all().order_by('parent_number')
204     extra_where = "catalogue_tag.category = 'theme'"
205     book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
206     extra_info = book.get_extra_info_value()
207
208     form = forms.SearchForm()
209     return render_to_response('catalogue/book_detail.html', locals(),
210         context_instance=RequestContext(request))
211
212
213 def book_stub_detail(request, slug):
214     book = get_object_or_404(models.BookStub, slug=slug)
215     pd_counter = book.pd
216     form = forms.SearchForm()
217
218     return render_to_response('catalogue/book_stub_detail.html', locals(),
219         context_instance=RequestContext(request))
220
221
222 def book_text(request, slug):
223     book = get_object_or_404(models.Book, slug=slug)
224     book_themes = {}
225     for fragment in book.fragments.all():
226         for theme in fragment.tags.filter(category='theme'):
227             book_themes.setdefault(theme, []).append(fragment)
228
229     book_themes = book_themes.items()
230     book_themes.sort(key=lambda s: s[0].sort_key)
231     return render_to_response('catalogue/book_text.html', locals(),
232         context_instance=RequestContext(request))
233
234
235 # ==========
236 # = Search =
237 # ==========
238
239 def _no_diacritics_regexp(query):
240     """ returns a regexp for searching for a query without diacritics
241     
242     should be locale-aware """
243     names = {
244         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źżŹŻ',
245         u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
246         }
247     def repl(m):
248         l = m.group()
249         return u"(%s)" % '|'.join(names[l])
250     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
251
252 def unicode_re_escape(query):
253     """ Unicode-friendly version of re.escape """
254     return re.sub('(?u)(\W)', r'\\\1', query)
255
256 def _word_starts_with(name, prefix):
257     """returns a Q object getting models having `name` contain a word
258     starting with `prefix`
259     
260     We define word characters as alphanumeric and underscore, like in JS.
261     
262     Works for MySQL, PostgreSQL, Oracle.
263     For SQLite, _sqlite* version is substituted for this.
264     """
265     kwargs = {}
266
267     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
268     # can't use [[:<:]] (word start), 
269     # but we want both `xy` and `(xy` to catch `(xyz)`
270     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
271
272     return Q(**kwargs)
273
274
275 def _sqlite_word_starts_with(name, prefix):
276     """ version of _word_starts_with for SQLite 
277     
278     SQLite in Django uses Python re module
279     """
280     kwargs = {}
281     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
282     kwargs['%s__iregex' % name] = ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
283     return Q(**kwargs)
284
285
286 if settings.DATABASE_ENGINE == 'sqlite3':
287     _word_starts_with = _sqlite_word_starts_with
288
289
290 def _tags_starting_with(prefix, user=None):
291     prefix = prefix.lower()
292     book_stubs = models.BookStub.objects.filter(_word_starts_with('title', prefix))
293     books = models.Book.objects.filter(_word_starts_with('title', prefix))
294     book_stubs = filter(lambda x: x not in books, book_stubs)
295     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
296     if user and user.is_authenticated():
297         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
298     else:
299         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
300
301     return list(books) + list(tags) + list(book_stubs)
302
303
304 def _get_result_link(match, tag_list):
305     if isinstance(match, models.Book) or isinstance(match, models.BookStub):
306         return match.get_absolute_url()
307     else:
308         return reverse('catalogue.views.tagged_object_list',
309             kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
310         )
311
312 def _get_result_type(match):
313     if isinstance(match, models.Book) or isinstance(match, models.BookStub):
314         type = 'book'
315     else:
316         type = match.category
317     return dict(models.TAG_CATEGORIES)[type]
318
319
320
321 def find_best_matches(query, user=None):
322     """ Finds a Book, Tag or Bookstub best matching a query.
323     
324     Returns a with:
325       - zero elements when nothing is found,
326       - one element when a best result is found,
327       - more then one element on multiple exact matches
328     
329     Raises a ValueError on too short a query.
330     """
331
332     query = query.lower()
333     if len(query) < 2:
334         raise ValueError("query must have at least two characters")
335
336     result = tuple(_tags_starting_with(query, user))
337     exact_matches = tuple(res for res in result if res.name.lower() == query)
338     if exact_matches:
339         return exact_matches
340     else:
341         return result[:1]
342
343
344 def search(request):
345     tags = request.GET.get('tags', '')
346     prefix = request.GET.get('q', '')
347
348     try:
349         tag_list = models.Tag.get_tag_list(tags)
350     except:
351         tag_list = []
352
353     try:
354         result = find_best_matches(prefix, request.user)
355     except ValueError:
356         return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
357             context_instance=RequestContext(request))
358
359     if len(result) == 1:
360         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
361     elif len(result) > 1:
362         return render_to_response('catalogue/search_multiple_hits.html',
363             {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
364             context_instance=RequestContext(request))
365     else:
366         return render_to_response('catalogue/search_no_hits.html', {'tags':tag_list, 'prefix':prefix},
367             context_instance=RequestContext(request))
368
369
370 def tags_starting_with(request):
371     prefix = request.GET.get('q', '')
372     # Prefix must have at least 2 characters
373     if len(prefix) < 2:
374         return HttpResponse('')
375
376     return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
377
378
379 # ====================
380 # = Shelf management =
381 # ====================
382 @login_required
383 @cache.never_cache
384 def user_shelves(request):
385     shelves = models.Tag.objects.filter(category='set', user=request.user)
386     new_set_form = forms.NewSetForm()
387     return render_to_response('catalogue/user_shelves.html', locals(),
388             context_instance=RequestContext(request))
389
390 @cache.never_cache
391 def book_sets(request, slug):
392     book = get_object_or_404(models.Book, slug=slug)
393     user_sets = models.Tag.objects.filter(category='set', user=request.user)
394     book_sets = book.tags.filter(category='set', user=request.user)
395
396     if not request.user.is_authenticated():
397         return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
398
399     if request.method == 'POST':
400         form = forms.ObjectSetsForm(book, request.user, request.POST)
401         if form.is_valid():
402             old_shelves = list(book.tags.filter(category='set'))
403             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
404
405             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
406                 shelf.book_count -= 1
407                 shelf.save()
408
409             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
410                 shelf.book_count += 1
411                 shelf.save()
412
413             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
414             if request.is_ajax():
415                 return HttpResponse(_('<p>Shelves were sucessfully saved.</p>'))
416             else:
417                 return HttpResponseRedirect('/')
418     else:
419         form = forms.ObjectSetsForm(book, request.user)
420         new_set_form = forms.NewSetForm()
421
422     return render_to_response('catalogue/book_sets.html', locals(),
423         context_instance=RequestContext(request))
424
425
426 @login_required
427 @require_POST
428 @cache.never_cache
429 def remove_from_shelf(request, shelf, book):
430     book = get_object_or_404(models.Book, slug=book)
431     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
432
433     if shelf in book.tags:
434         models.Tag.objects.remove_tag(book, shelf)
435
436         shelf.book_count -= 1
437         shelf.save()
438
439         return HttpResponse(_('Book was successfully removed from the shelf'))
440     else:
441         return HttpResponse(_('This book is not on the shelf'))
442
443
444 def collect_books(books):
445     """
446     Returns all real books in collection.
447     """
448     result = []
449     for book in books:
450         if len(book.children.all()) == 0:
451             result.append(book)
452         else:
453             result += collect_books(book.children.all())
454     return result
455
456
457 @cache.never_cache
458 def download_shelf(request, slug):
459     """"
460     Create a ZIP archive on disk and transmit it in chunks of 8KB,
461     without loading the whole file into memory. A similar approach can
462     be used for large dynamic PDF files.                                        
463     """
464     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
465
466     formats = []
467     form = forms.DownloadFormatsForm(request.GET)
468     if form.is_valid():
469         formats = form.cleaned_data['formats']
470     if len(formats) == 0:
471         formats = ['pdf', 'epub', 'odt', 'txt', 'mp3', 'ogg']
472
473     # Create a ZIP archive
474     temp = tempfile.TemporaryFile()
475     archive = zipfile.ZipFile(temp, 'w')
476
477     for book in collect_books(models.Book.tagged.with_all(shelf)):
478         if 'pdf' in formats and book.pdf_file:
479             filename = book.pdf_file.path
480             archive.write(filename, str('%s.pdf' % book.slug))
481         if 'epub' in formats and book.epub_file:
482             filename = book.epub_file.path
483             archive.write(filename, str('%s.epub' % book.slug))
484         if 'odt' in formats and book.odt_file:
485             filename = book.odt_file.path
486             archive.write(filename, str('%s.odt' % book.slug))
487         if 'txt' in formats and book.txt_file:
488             filename = book.txt_file.path
489             archive.write(filename, str('%s.txt' % book.slug))
490         if 'mp3' in formats and book.mp3_file:
491             filename = book.mp3_file.path
492             archive.write(filename, str('%s.mp3' % book.slug))
493         if 'ogg' in formats and book.ogg_file:
494             filename = book.ogg_file.path
495             archive.write(filename, str('%s.ogg' % book.slug))
496     archive.close()
497
498     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
499     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
500     response['Content-Length'] = temp.tell()
501
502     temp.seek(0)
503     response.write(temp.read())
504     return response
505
506
507 @cache.never_cache
508 def shelf_book_formats(request, shelf):
509     """"
510     Returns a list of formats of books in shelf.
511     """
512     shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
513
514     formats = {'pdf': False, 'epub': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
515
516     for book in collect_books(models.Book.tagged.with_all(shelf)):
517         if book.pdf_file:
518             formats['pdf'] = True
519         if book.epub_file:
520             formats['epub'] = True
521         if book.odt_file:
522             formats['odt'] = True
523         if book.txt_file:
524             formats['txt'] = True
525         if book.mp3_file:
526             formats['mp3'] = True
527         if book.ogg_file:
528             formats['ogg'] = True
529
530     return HttpResponse(LazyEncoder().encode(formats))
531
532
533 @login_required
534 @require_POST
535 @cache.never_cache
536 def new_set(request):
537     new_set_form = forms.NewSetForm(request.POST)
538     if new_set_form.is_valid():
539         new_set = new_set_form.save(request.user)
540
541         if request.is_ajax():
542             return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully created</p>') % new_set)
543         else:
544             return HttpResponseRedirect('/')
545
546     return HttpResponseRedirect('/')
547
548
549 @login_required
550 @require_POST
551 @cache.never_cache
552 def delete_shelf(request, slug):
553     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
554     user_set.delete()
555
556     if request.is_ajax():
557         return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
558     else:
559         return HttpResponseRedirect('/')
560
561
562 # ==================
563 # = Authentication =
564 # ==================
565 @require_POST
566 @cache.never_cache
567 def login(request):
568     form = AuthenticationForm(data=request.POST, prefix='login')
569     if form.is_valid():
570         auth.login(request, form.get_user())
571         response_data = {'success': True, 'errors': {}}
572     else:
573         response_data = {'success': False, 'errors': form.errors}
574     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
575
576
577 @require_POST
578 @cache.never_cache
579 def register(request):
580     registration_form = UserCreationForm(request.POST, prefix='registration')
581     if registration_form.is_valid():
582         user = registration_form.save()
583         user = auth.authenticate(
584             username=registration_form.cleaned_data['username'],
585             password=registration_form.cleaned_data['password1']
586         )
587         auth.login(request, user)
588         response_data = {'success': True, 'errors': {}}
589     else:
590         response_data = {'success': False, 'errors': registration_form.errors}
591     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
592
593
594 @cache.never_cache
595 def logout_then_redirect(request):
596     auth.logout(request)
597     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
598
599
600
601 # =========
602 # = Admin =
603 # =========
604 @login_required
605 @staff_required
606 def import_book(request):
607     """docstring for import_book"""
608     book_import_form = forms.BookImportForm(request.POST, request.FILES)
609     if book_import_form.is_valid():
610         try:
611             book_import_form.save()
612         except:
613             info = sys.exc_info()
614             exception = pprint.pformat(info[1])
615             tb = '\n'.join(traceback.format_tb(info[2]))
616             _('Today is %(month)s, %(day)s.') % {'month': m, 'day': d}
617             return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
618         return HttpResponse(_("Book imported successfully"))
619     else:
620         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
621
622
623
624 def clock(request):
625     """ Provides server time for jquery.countdown,
626     in a format suitable for Date.parse()
627     """
628     from datetime import datetime
629     return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))