1 # -*- coding: utf-8 -*-
5 from django.template import RequestContext
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponse, HttpResponseRedirect, Http404
8 from django.core.urlresolvers import reverse
9 from django.db.models import Q
10 from django.contrib.auth.decorators import login_required, user_passes_test
11 from django.utils.datastructures import SortedDict
12 from django.views.decorators.http import require_POST
13 from django.contrib import auth
14 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
15 from django.utils import simplejson
16 from django.utils.functional import Promise
17 from django.utils.encoding import force_unicode
18 from django.views.decorators import cache
20 from catalogue import models
21 from catalogue import forms
22 from catalogue.utils import split_tags
23 from newtagging import views as newtagging_views
26 staff_required = user_passes_test(lambda user: user.is_staff)
29 class LazyEncoder(simplejson.JSONEncoder):
30 def default(self, obj):
31 if isinstance(obj, Promise):
32 return force_unicode(obj)
36 def main_page(request):
37 if request.user.is_authenticated():
38 shelves = models.Tag.objects.filter(category='set', user=request.user)
39 new_set_form = forms.NewSetForm()
40 extra_where = 'NOT catalogue_tag.category = "set"'
41 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
42 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
43 extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
44 categories = split_tags(tags)
46 form = forms.SearchForm()
47 return render_to_response('catalogue/main_page.html', locals(),
48 context_instance=RequestContext(request))
51 def book_list(request):
52 books = models.Book.objects.all()
53 form = forms.SearchForm()
55 books_by_first_letter = SortedDict()
57 books_by_first_letter.setdefault(book.title[0], []).append(book)
59 return render_to_response('catalogue/book_list.html', locals(),
60 context_instance=RequestContext(request))
63 def tagged_object_list(request, tags=''):
64 # Prevent DoS attacks on our database
65 if len(tags.split('/')) > 6:
69 tags = models.Tag.get_tag_list(tags)
70 except models.Tag.DoesNotExist:
73 if len([tag for tag in tags if tag.category == 'book']):
77 shelf = [tag for tag in tags if tag.category == 'set']
78 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
79 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
81 model = models.Fragment
83 user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
85 extra_where = 'catalogue_tag.category NOT IN ("set", "book")'
86 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
87 categories = split_tags(related_tags)
89 if not (theme_is_set or shelf_is_set):
90 model=models.Book.objects.filter(parent=None)
92 return newtagging_views.tagged_object_list(
95 queryset_or_model=model,
97 template_name='catalogue/tagged_object_list.html',
98 extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set, 'user_is_owner': user_is_owner },
102 def book_fragments(request, book_slug, theme_slug):
103 book = get_object_or_404(models.Book, slug=book_slug)
104 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
105 theme = get_object_or_404(models.Tag, slug=theme_slug)
106 fragments = models.Fragment.tagged.with_all([book_tag, theme])
108 form = forms.SearchForm()
109 return render_to_response('catalogue/book_fragments.html', locals(),
110 context_instance=RequestContext(request))
113 def book_detail(request, slug):
114 book = get_object_or_404(models.Book, slug=slug)
115 book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
116 tags = list(book.tags.filter(~Q(category='set')))
117 categories = split_tags(tags)
118 book_children = book.children.all().order_by('parent_number')
119 extra_where = 'catalogue_tag.category = "theme"'
120 book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
121 extra_info = book.get_extra_info_value()
123 form = forms.SearchForm()
124 return render_to_response('catalogue/book_detail.html', locals(),
125 context_instance=RequestContext(request))
128 def book_text(request, slug):
129 book = get_object_or_404(models.Book, slug=slug)
131 for fragment in book.fragments.all():
132 for theme in fragment.tags.filter(category='theme'):
133 book_themes.setdefault(theme, []).append(fragment)
135 book_themes = book_themes.items()
136 book_themes.sort(key=lambda s: s[0].sort_key)
137 return render_to_response('catalogue/book_text.html', locals(),
138 context_instance=RequestContext(request))
144 def _tags_starting_with(prefix, user):
145 books = models.Book.objects.filter(title__icontains=prefix)
146 tags = models.Tag.objects.filter(name__icontains=prefix)
147 if user.is_authenticated():
148 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
150 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
152 return list(books) + list(tags)
156 tags = request.GET.get('tags', '')
157 prefix = request.GET.get('q', '')
158 # Prefix must have at least 2 characters
160 return HttpResponse('')
163 tag_list = models.Tag.get_tag_list(tags)
167 result = _tags_starting_with(prefix, request.user)
170 if isinstance(tag, models.Book):
171 return HttpResponseRedirect(tag.get_absolute_url())
175 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
176 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
180 def tags_starting_with(request):
181 prefix = request.GET.get('q', '')
182 # Prefix must have at least 2 characters
184 return HttpResponse('')
186 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
189 # ====================
190 # = Shelf management =
191 # ====================
194 def user_shelves(request):
195 shelves = models.Tag.objects.filter(category='set', user=request.user)
196 new_set_form = forms.NewSetForm()
197 return render_to_response('catalogue/user_shelves.html', locals(),
198 context_instance=RequestContext(request))
201 def book_sets(request, slug):
202 book = get_object_or_404(models.Book, slug=slug)
203 user_sets = models.Tag.objects.filter(category='set', user=request.user)
204 book_sets = book.tags.filter(category='set', user=request.user)
206 if not request.user.is_authenticated():
207 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
209 if request.method == 'POST':
210 form = forms.ObjectSetsForm(book, request.user, request.POST)
212 old_shelves = list(book.tags.filter(category='set'))
213 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
215 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
216 shelf.book_count -= 1
219 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
220 shelf.book_count += 1
223 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
224 if request.is_ajax():
225 return HttpResponse('<p>Półki zostały zapisane.</p>')
227 return HttpResponseRedirect('/')
229 form = forms.ObjectSetsForm(book, request.user)
230 new_set_form = forms.NewSetForm()
232 return render_to_response('catalogue/book_sets.html', locals(),
233 context_instance=RequestContext(request))
239 def remove_from_shelf(request, shelf, book):
240 book = get_object_or_404(models.Book, slug=book)
241 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
243 models.Tag.objects.remove_tag(book, shelf)
245 shelf.book_count -= 1
248 return HttpResponse('Usunieto')
252 def download_shelf(request, slug):
254 Create a ZIP archive on disk and transmit it in chunks of 8KB,
255 without loading the whole file into memory. A similar approach can
256 be used for large dynamic PDF files.
258 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
260 # Create a ZIP archive
261 temp = temp = tempfile.TemporaryFile()
262 archive = zipfile.ZipFile(temp, 'w')
264 # Collect all books to include in ZIP archive
265 def collect_books(books):
268 if len(book.children.all()) == 0:
271 result += collect_books(book.children.all())
274 for book in collect_books(models.Book.tagged.with_all(shelf)):
276 filename = book.pdf_file.path
277 archive.write(filename, str('%s.pdf' % book.slug))
279 filename = book.odt_file.path
280 archive.write(filename, str('%s.odt' % book.slug))
282 filename = book.txt_file.path
283 archive.write(filename, str('%s.txt' % book.slug))
286 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
287 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
288 response['Content-Length'] = temp.tell()
291 response.write(temp.read())
298 def new_set(request):
299 new_set_form = forms.NewSetForm(request.POST)
300 if new_set_form.is_valid():
301 new_set = new_set_form.save(request.user)
303 if request.is_ajax():
304 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
306 return HttpResponseRedirect('/')
308 return HttpResponseRedirect('/')
314 def delete_shelf(request, slug):
315 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
318 if request.is_ajax():
319 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
321 return HttpResponseRedirect('/')
330 form = AuthenticationForm(data=request.POST, prefix='login')
332 auth.login(request, form.get_user())
333 response_data = {'success': True, 'errors': {}}
335 response_data = {'success': False, 'errors': form.errors}
336 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
341 def register(request):
342 registration_form = UserCreationForm(request.POST, prefix='registration')
343 if registration_form.is_valid():
344 user = registration_form.save()
345 user = auth.authenticate(
346 username=registration_form.cleaned_data['username'],
347 password=registration_form.cleaned_data['password1']
349 auth.login(request, user)
350 response_data = {'success': True, 'errors': {}}
352 response_data = {'success': False, 'errors': registration_form.errors}
353 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
357 def logout_then_redirect(request):
359 return HttpResponseRedirect(request.GET.get('next', '/'))
368 def import_book(request):
369 """docstring for import_book"""
370 book_import_form = forms.BookImportForm(request.POST, request.FILES)
371 if book_import_form.is_valid():
373 book_import_form.save()
375 # return HttpResponse("Error importing book: %r" % (sys.exc_info(),))
376 return HttpResponse("Book imported successfully")
378 return HttpResponse("Error importing file: %r" % book_import_form.errors)