1 # -*- coding: utf-8 -*-
8 from django.template import RequestContext
9 from django.shortcuts import render_to_response, get_object_or_404
10 from django.http import HttpResponse, HttpResponseRedirect, Http404
11 from django.core.urlresolvers import reverse
12 from django.db.models import Q
13 from django.contrib.auth.decorators import login_required, user_passes_test
14 from django.utils.datastructures import SortedDict
15 from django.views.decorators.http import require_POST
16 from django.contrib import auth
17 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
18 from django.utils import simplejson
19 from django.utils.functional import Promise
20 from django.utils.encoding import force_unicode
21 from django.views.decorators import cache
23 from catalogue import models
24 from catalogue import forms
25 from catalogue.utils import split_tags
26 from newtagging import views as newtagging_views
29 staff_required = user_passes_test(lambda user: user.is_staff)
32 class LazyEncoder(simplejson.JSONEncoder):
33 def default(self, obj):
34 if isinstance(obj, Promise):
35 return force_unicode(obj)
39 def main_page(request):
40 if request.user.is_authenticated():
41 shelves = models.Tag.objects.filter(category='set', user=request.user)
42 new_set_form = forms.NewSetForm()
43 extra_where = 'NOT catalogue_tag.category = "set"'
44 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
45 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
46 extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
47 categories = split_tags(tags)
49 form = forms.SearchForm()
50 return render_to_response('catalogue/main_page.html', locals(),
51 context_instance=RequestContext(request))
54 def book_list(request):
55 books = models.Book.objects.all()
56 form = forms.SearchForm()
58 books_by_first_letter = SortedDict()
60 books_by_first_letter.setdefault(book.title[0], []).append(book)
62 return render_to_response('catalogue/book_list.html', locals(),
63 context_instance=RequestContext(request))
66 def tagged_object_list(request, tags=''):
67 # Prevent DoS attacks on our database
68 if len(tags.split('/')) > 6:
72 tags = models.Tag.get_tag_list(tags)
73 except models.Tag.DoesNotExist:
76 if len([tag for tag in tags if tag.category == 'book']):
80 shelf = [tag for tag in tags if tag.category == 'set']
81 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
82 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
84 model = models.Fragment
86 user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
88 extra_where = 'catalogue_tag.category NOT IN ("set", "book")'
89 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
90 categories = split_tags(related_tags)
92 if not (theme_is_set or shelf_is_set):
93 model=models.Book.objects.filter(parent=None)
95 return newtagging_views.tagged_object_list(
98 queryset_or_model=model,
100 template_name='catalogue/tagged_object_list.html',
102 'categories': categories,
103 'shelf_is_set': shelf_is_set,
104 'user_is_owner': user_is_owner,
105 'formats_form': forms.DownloadFormatsForm(),
110 def book_fragments(request, book_slug, theme_slug):
111 book = get_object_or_404(models.Book, slug=book_slug)
112 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
113 theme = get_object_or_404(models.Tag, slug=theme_slug)
114 fragments = models.Fragment.tagged.with_all([book_tag, theme])
116 form = forms.SearchForm()
117 return render_to_response('catalogue/book_fragments.html', locals(),
118 context_instance=RequestContext(request))
121 def book_detail(request, slug):
122 book = get_object_or_404(models.Book, slug=slug)
123 book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
124 tags = list(book.tags.filter(~Q(category='set')))
125 categories = split_tags(tags)
126 book_children = book.children.all().order_by('parent_number')
127 extra_where = 'catalogue_tag.category = "theme"'
128 book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
129 extra_info = book.get_extra_info_value()
131 form = forms.SearchForm()
132 return render_to_response('catalogue/book_detail.html', locals(),
133 context_instance=RequestContext(request))
136 def book_text(request, slug):
137 book = get_object_or_404(models.Book, slug=slug)
139 for fragment in book.fragments.all():
140 for theme in fragment.tags.filter(category='theme'):
141 book_themes.setdefault(theme, []).append(fragment)
143 book_themes = book_themes.items()
144 book_themes.sort(key=lambda s: s[0].sort_key)
145 return render_to_response('catalogue/book_text.html', locals(),
146 context_instance=RequestContext(request))
152 def _tags_starting_with(prefix, user):
153 books = models.Book.objects.filter(title__icontains=prefix)
154 tags = models.Tag.objects.filter(name__icontains=prefix)
155 if user.is_authenticated():
156 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
158 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
160 return list(books) + list(tags)
164 tags = request.GET.get('tags', '')
165 prefix = request.GET.get('q', '')
166 # Prefix must have at least 2 characters
168 return HttpResponse('')
171 tag_list = models.Tag.get_tag_list(tags)
175 result = _tags_starting_with(prefix, request.user)
178 if isinstance(tag, models.Book):
179 return HttpResponseRedirect(tag.get_absolute_url())
183 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
184 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
188 def tags_starting_with(request):
189 prefix = request.GET.get('q', '')
190 # Prefix must have at least 2 characters
192 return HttpResponse('')
194 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
197 # ====================
198 # = Shelf management =
199 # ====================
202 def user_shelves(request):
203 shelves = models.Tag.objects.filter(category='set', user=request.user)
204 new_set_form = forms.NewSetForm()
205 return render_to_response('catalogue/user_shelves.html', locals(),
206 context_instance=RequestContext(request))
209 def book_sets(request, slug):
210 book = get_object_or_404(models.Book, slug=slug)
211 user_sets = models.Tag.objects.filter(category='set', user=request.user)
212 book_sets = book.tags.filter(category='set', user=request.user)
214 if not request.user.is_authenticated():
215 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
217 if request.method == 'POST':
218 form = forms.ObjectSetsForm(book, request.user, request.POST)
220 old_shelves = list(book.tags.filter(category='set'))
221 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
223 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
224 shelf.book_count -= 1
227 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
228 shelf.book_count += 1
231 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
232 if request.is_ajax():
233 return HttpResponse('<p>Półki zostały zapisane.</p>')
235 return HttpResponseRedirect('/')
237 form = forms.ObjectSetsForm(book, request.user)
238 new_set_form = forms.NewSetForm()
240 return render_to_response('catalogue/book_sets.html', locals(),
241 context_instance=RequestContext(request))
247 def remove_from_shelf(request, shelf, book):
248 book = get_object_or_404(models.Book, slug=book)
249 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
251 models.Tag.objects.remove_tag(book, shelf)
253 shelf.book_count -= 1
256 return HttpResponse('Usunieto')
259 def collect_books(books):
261 Returns all real books in collection.
265 if len(book.children.all()) == 0:
268 result += collect_books(book.children.all())
273 def download_shelf(request, slug):
275 Create a ZIP archive on disk and transmit it in chunks of 8KB,
276 without loading the whole file into memory. A similar approach can
277 be used for large dynamic PDF files.
279 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
282 form = forms.DownloadFormatsForm(request.GET)
284 formats = form.cleaned_data['formats']
285 if len(formats) == 0:
286 formats = ['pdf', 'odt', 'txt', 'mp3', 'ogg']
288 # Create a ZIP archive
289 temp = temp = tempfile.TemporaryFile()
290 archive = zipfile.ZipFile(temp, 'w')
292 for book in collect_books(models.Book.tagged.with_all(shelf)):
293 if 'pdf' in formats and book.pdf_file:
294 filename = book.pdf_file.path
295 archive.write(filename, str('%s.pdf' % book.slug))
296 if 'odt' in formats and book.odt_file:
297 filename = book.odt_file.path
298 archive.write(filename, str('%s.odt' % book.slug))
299 if 'txt' in formats and book.txt_file:
300 filename = book.txt_file.path
301 archive.write(filename, str('%s.txt' % book.slug))
302 if 'mp3' in formats and book.mp3_file:
303 filename = book.mp3_file.path
304 archive.write(filename, str('%s.mp3' % book.slug))
305 if 'ogg' in formats and book.ogg_file:
306 filename = book.ogg_file.path
307 archive.write(filename, str('%s.ogg' % book.slug))
310 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
311 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
312 response['Content-Length'] = temp.tell()
315 response.write(temp.read())
320 def shelf_book_formats(request, shelf):
322 Returns a list of formats of books in shelf.
324 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
326 formats = {'pdf': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
328 for book in collect_books(models.Book.tagged.with_all(shelf)):
330 formats['pdf'] = True
332 formats['odt'] = True
334 formats['txt'] = True
336 formats['mp3'] = True
338 formats['ogg'] = True
340 return HttpResponse(LazyEncoder().encode(formats))
346 def new_set(request):
347 new_set_form = forms.NewSetForm(request.POST)
348 if new_set_form.is_valid():
349 new_set = new_set_form.save(request.user)
351 if request.is_ajax():
352 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
354 return HttpResponseRedirect('/')
356 return HttpResponseRedirect('/')
362 def delete_shelf(request, slug):
363 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
366 if request.is_ajax():
367 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
369 return HttpResponseRedirect('/')
378 form = AuthenticationForm(data=request.POST, prefix='login')
380 auth.login(request, form.get_user())
381 response_data = {'success': True, 'errors': {}}
383 response_data = {'success': False, 'errors': form.errors}
384 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
389 def register(request):
390 registration_form = UserCreationForm(request.POST, prefix='registration')
391 if registration_form.is_valid():
392 user = registration_form.save()
393 user = auth.authenticate(
394 username=registration_form.cleaned_data['username'],
395 password=registration_form.cleaned_data['password1']
397 auth.login(request, user)
398 response_data = {'success': True, 'errors': {}}
400 response_data = {'success': False, 'errors': registration_form.errors}
401 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
405 def logout_then_redirect(request):
407 return HttpResponseRedirect(request.GET.get('next', '/'))
416 def import_book(request):
417 """docstring for import_book"""
418 book_import_form = forms.BookImportForm(request.POST, request.FILES)
419 if book_import_form.is_valid():
421 book_import_form.save()
423 info = sys.exc_info()
424 exception = pprint.pformat(info[1])
425 tb = '\n'.join(traceback.format_tb(info[2]))
426 return HttpResponse("An error occurred: %s\n\n%s" % (exception, tb), mimetype='text/plain')
427 return HttpResponse("Book imported successfully")
429 return HttpResponse("Error importing file: %r" % book_import_form.errors)