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