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.
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
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
32 staff_required = user_passes_test(lambda user: user.is_staff)
35 class LazyEncoder(simplejson.JSONEncoder):
36 def default(self, obj):
37 if isinstance(obj, Promise):
38 return force_unicode(obj)
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)
52 form = forms.SearchForm()
53 return render_to_response('catalogue/main_page.html', locals(),
54 context_instance=RequestContext(request))
57 def book_list(request):
58 books = models.Book.objects.all()
59 form = forms.SearchForm()
61 books_by_first_letter = SortedDict()
63 books_by_first_letter.setdefault(book.title[0], []).append(book)
65 return render_to_response('catalogue/book_list.html', locals(),
66 context_instance=RequestContext(request))
69 def tagged_object_list(request, tags=''):
70 # Prevent DoS attacks on our database
71 if len(tags.split('/')) > 6:
75 tags = models.Tag.get_tag_list(tags)
76 except models.Tag.DoesNotExist:
79 if len([tag for tag in tags if tag.category == '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
87 model = models.Fragment
89 user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
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)
95 if not (theme_is_set or shelf_is_set):
96 model=models.Book.objects.filter(parent=None)
98 return newtagging_views.tagged_object_list(
100 tag_model=models.Tag,
101 queryset_or_model=model,
103 template_name='catalogue/tagged_object_list.html',
105 'categories': categories,
106 'shelf_is_set': shelf_is_set,
107 'user_is_owner': user_is_owner,
108 'formats_form': forms.DownloadFormatsForm(),
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])
119 form = forms.SearchForm()
120 return render_to_response('catalogue/book_fragments.html', locals(),
121 context_instance=RequestContext(request))
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()
134 form = forms.SearchForm()
135 return render_to_response('catalogue/book_detail.html', locals(),
136 context_instance=RequestContext(request))
139 def book_text(request, slug):
140 book = get_object_or_404(models.Book, slug=slug)
142 for fragment in book.fragments.all():
143 for theme in fragment.tags.filter(category='theme'):
144 book_themes.setdefault(theme, []).append(fragment)
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))
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)))
161 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
163 return list(books) + list(tags)
167 tags = request.GET.get('tags', '')
168 prefix = request.GET.get('q', '')
169 # Prefix must have at least 2 characters
171 return HttpResponse('')
174 tag_list = models.Tag.get_tag_list(tags)
178 result = _tags_starting_with(prefix, request.user)
181 if isinstance(tag, models.Book):
182 return HttpResponseRedirect(tag.get_absolute_url())
186 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
187 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
191 def tags_starting_with(request):
192 prefix = request.GET.get('q', '')
193 # Prefix must have at least 2 characters
195 return HttpResponse('')
197 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
200 # ====================
201 # = Shelf management =
202 # ====================
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))
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)
217 if not request.user.is_authenticated():
218 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
220 if request.method == 'POST':
221 form = forms.ObjectSetsForm(book, request.user, request.POST)
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']]
226 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
227 shelf.book_count -= 1
230 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
231 shelf.book_count += 1
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>')
238 return HttpResponseRedirect('/')
240 form = forms.ObjectSetsForm(book, request.user)
241 new_set_form = forms.NewSetForm()
243 return render_to_response('catalogue/book_sets.html', locals(),
244 context_instance=RequestContext(request))
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)
254 models.Tag.objects.remove_tag(book, shelf)
256 shelf.book_count -= 1
259 return HttpResponse('Usunieto')
262 def collect_books(books):
264 Returns all real books in collection.
268 if len(book.children.all()) == 0:
271 result += collect_books(book.children.all())
276 def download_shelf(request, slug):
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.
282 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
285 form = forms.DownloadFormatsForm(request.GET)
287 formats = form.cleaned_data['formats']
288 if len(formats) == 0:
289 formats = ['pdf', 'odt', 'txt', 'mp3', 'ogg']
291 # Create a ZIP archive
292 temp = temp = tempfile.TemporaryFile()
293 archive = zipfile.ZipFile(temp, 'w')
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))
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()
318 response.write(temp.read())
323 def shelf_book_formats(request, shelf):
325 Returns a list of formats of books in shelf.
327 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
329 formats = {'pdf': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
331 for book in collect_books(models.Book.tagged.with_all(shelf)):
333 formats['pdf'] = True
335 formats['odt'] = True
337 formats['txt'] = True
339 formats['mp3'] = True
341 formats['ogg'] = True
343 return HttpResponse(LazyEncoder().encode(formats))
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)
354 if request.is_ajax():
355 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
357 return HttpResponseRedirect('/')
359 return HttpResponseRedirect('/')
365 def delete_shelf(request, slug):
366 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
369 if request.is_ajax():
370 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
372 return HttpResponseRedirect('/')
381 form = AuthenticationForm(data=request.POST, prefix='login')
383 auth.login(request, form.get_user())
384 response_data = {'success': True, 'errors': {}}
386 response_data = {'success': False, 'errors': form.errors}
387 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
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']
400 auth.login(request, user)
401 response_data = {'success': True, 'errors': {}}
403 response_data = {'success': False, 'errors': registration_form.errors}
404 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
408 def logout_then_redirect(request):
410 return HttpResponseRedirect(request.GET.get('next', '/'))
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():
424 book_import_form.save()
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")
432 return HttpResponse("Error importing file: %r" % book_import_form.errors)