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