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