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