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',
101 extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set, 'user_is_owner': user_is_owner },
105 def book_fragments(request, book_slug, theme_slug):
106 book = get_object_or_404(models.Book, slug=book_slug)
107 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
108 theme = get_object_or_404(models.Tag, slug=theme_slug)
109 fragments = models.Fragment.tagged.with_all([book_tag, theme])
111 form = forms.SearchForm()
112 return render_to_response('catalogue/book_fragments.html', locals(),
113 context_instance=RequestContext(request))
116 def book_detail(request, slug):
117 book = get_object_or_404(models.Book, slug=slug)
118 book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
119 tags = list(book.tags.filter(~Q(category='set')))
120 categories = split_tags(tags)
121 book_children = book.children.all().order_by('parent_number')
122 extra_where = 'catalogue_tag.category = "theme"'
123 book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
124 extra_info = book.get_extra_info_value()
126 form = forms.SearchForm()
127 return render_to_response('catalogue/book_detail.html', locals(),
128 context_instance=RequestContext(request))
131 def book_text(request, slug):
132 book = get_object_or_404(models.Book, slug=slug)
134 for fragment in book.fragments.all():
135 for theme in fragment.tags.filter(category='theme'):
136 book_themes.setdefault(theme, []).append(fragment)
138 book_themes = book_themes.items()
139 book_themes.sort(key=lambda s: s[0].sort_key)
140 return render_to_response('catalogue/book_text.html', locals(),
141 context_instance=RequestContext(request))
147 def _tags_starting_with(prefix, user):
148 books = models.Book.objects.filter(title__icontains=prefix)
149 tags = models.Tag.objects.filter(name__icontains=prefix)
150 if user.is_authenticated():
151 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
153 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
155 return list(books) + list(tags)
159 tags = request.GET.get('tags', '')
160 prefix = request.GET.get('q', '')
161 # Prefix must have at least 2 characters
163 return HttpResponse('')
166 tag_list = models.Tag.get_tag_list(tags)
170 result = _tags_starting_with(prefix, request.user)
173 if isinstance(tag, models.Book):
174 return HttpResponseRedirect(tag.get_absolute_url())
178 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
179 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
183 def tags_starting_with(request):
184 prefix = request.GET.get('q', '')
185 # Prefix must have at least 2 characters
187 return HttpResponse('')
189 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
192 # ====================
193 # = Shelf management =
194 # ====================
197 def user_shelves(request):
198 shelves = models.Tag.objects.filter(category='set', user=request.user)
199 new_set_form = forms.NewSetForm()
200 return render_to_response('catalogue/user_shelves.html', locals(),
201 context_instance=RequestContext(request))
204 def book_sets(request, slug):
205 book = get_object_or_404(models.Book, slug=slug)
206 user_sets = models.Tag.objects.filter(category='set', user=request.user)
207 book_sets = book.tags.filter(category='set', user=request.user)
209 if not request.user.is_authenticated():
210 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
212 if request.method == 'POST':
213 form = forms.ObjectSetsForm(book, request.user, request.POST)
215 old_shelves = list(book.tags.filter(category='set'))
216 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
218 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
219 shelf.book_count -= 1
222 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
223 shelf.book_count += 1
226 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
227 if request.is_ajax():
228 return HttpResponse('<p>Półki zostały zapisane.</p>')
230 return HttpResponseRedirect('/')
232 form = forms.ObjectSetsForm(book, request.user)
233 new_set_form = forms.NewSetForm()
235 return render_to_response('catalogue/book_sets.html', locals(),
236 context_instance=RequestContext(request))
242 def remove_from_shelf(request, shelf, book):
243 book = get_object_or_404(models.Book, slug=book)
244 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
246 models.Tag.objects.remove_tag(book, shelf)
248 shelf.book_count -= 1
251 return HttpResponse('Usunieto')
255 def download_shelf(request, slug):
257 Create a ZIP archive on disk and transmit it in chunks of 8KB,
258 without loading the whole file into memory. A similar approach can
259 be used for large dynamic PDF files.
261 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
263 # Create a ZIP archive
264 temp = temp = tempfile.TemporaryFile()
265 archive = zipfile.ZipFile(temp, 'w')
267 # Collect all books to include in ZIP archive
268 def collect_books(books):
271 if len(book.children.all()) == 0:
274 result += collect_books(book.children.all())
277 for book in collect_books(models.Book.tagged.with_all(shelf)):
279 filename = book.pdf_file.path
280 archive.write(filename, str('%s.pdf' % book.slug))
282 filename = book.odt_file.path
283 archive.write(filename, str('%s.odt' % book.slug))
285 filename = book.txt_file.path
286 archive.write(filename, str('%s.txt' % book.slug))
289 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
290 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
291 response['Content-Length'] = temp.tell()
294 response.write(temp.read())
301 def new_set(request):
302 new_set_form = forms.NewSetForm(request.POST)
303 if new_set_form.is_valid():
304 new_set = new_set_form.save(request.user)
306 if request.is_ajax():
307 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
309 return HttpResponseRedirect('/')
311 return HttpResponseRedirect('/')
317 def delete_shelf(request, slug):
318 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
321 if request.is_ajax():
322 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
324 return HttpResponseRedirect('/')
333 form = AuthenticationForm(data=request.POST, prefix='login')
335 auth.login(request, form.get_user())
336 response_data = {'success': True, 'errors': {}}
338 response_data = {'success': False, 'errors': form.errors}
339 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
344 def register(request):
345 registration_form = UserCreationForm(request.POST, prefix='registration')
346 if registration_form.is_valid():
347 user = registration_form.save()
348 user = auth.authenticate(
349 username=registration_form.cleaned_data['username'],
350 password=registration_form.cleaned_data['password1']
352 auth.login(request, user)
353 response_data = {'success': True, 'errors': {}}
355 response_data = {'success': False, 'errors': registration_form.errors}
356 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
360 def logout_then_redirect(request):
362 return HttpResponseRedirect(request.GET.get('next', '/'))
371 def import_book(request):
372 """docstring for import_book"""
373 book_import_form = forms.BookImportForm(request.POST, request.FILES)
374 if book_import_form.is_valid():
376 book_import_form.save()
378 info = sys.exc_info()
379 exception = pprint.pformat(info[1])
380 tb = '\n'.join(traceback.format_tb(info[2]))
381 return HttpResponse("An error occurred: %s\n\n%s" % (exception, tb), mimetype='text/plain')
382 return HttpResponse("Book imported successfully")
384 return HttpResponse("Error importing file: %r" % book_import_form.errors)