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