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
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 class LazyEncoder(simplejson.JSONEncoder):
27 def default(self, obj):
28 if isinstance(obj, Promise):
29 return force_unicode(obj)
33 def main_page(request):
34 if request.user.is_authenticated():
35 shelves = models.Tag.objects.filter(category='set', user=request.user)
36 new_set_form = forms.NewSetForm()
37 extra_where = 'NOT catalogue_tag.category = "set"'
38 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
39 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
40 extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
41 categories = split_tags(tags)
43 form = forms.SearchForm()
44 return render_to_response('catalogue/main_page.html', locals(),
45 context_instance=RequestContext(request))
48 def book_list(request):
49 books = models.Book.objects.all()
50 form = forms.SearchForm()
52 books_by_first_letter = SortedDict()
54 books_by_first_letter.setdefault(book.title[0], []).append(book)
56 return render_to_response('catalogue/book_list.html', locals(),
57 context_instance=RequestContext(request))
60 def tagged_object_list(request, tags=''):
61 # Prevent DoS attacks on our database
62 if len(tags.split('/')) > 6:
66 tags = models.Tag.get_tag_list(tags)
67 except models.Tag.DoesNotExist:
70 if len([tag for tag in tags if tag.category == 'book']):
74 shelf = [tag for tag in tags if tag.category == 'set']
75 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
76 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
78 model = models.Fragment
80 user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
82 extra_where = 'catalogue_tag.category NOT IN ("set", "book")'
83 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
84 categories = split_tags(related_tags)
86 if not (theme_is_set or shelf_is_set):
87 model=models.Book.objects.filter(parent=None)
89 return newtagging_views.tagged_object_list(
92 queryset_or_model=model,
94 template_name='catalogue/tagged_object_list.html',
95 extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set, 'user_is_owner': user_is_owner },
99 def book_fragments(request, book_slug, theme_slug):
100 book = get_object_or_404(models.Book, slug=book_slug)
101 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
102 theme = get_object_or_404(models.Tag, slug=theme_slug)
103 fragments = models.Fragment.tagged.with_all([book_tag, theme])
105 form = forms.SearchForm()
106 return render_to_response('catalogue/book_fragments.html', locals(),
107 context_instance=RequestContext(request))
110 def book_detail(request, slug):
111 book = get_object_or_404(models.Book, slug=slug)
112 book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
113 tags = list(book.tags.filter(~Q(category='set')))
114 categories = split_tags(tags)
115 book_children = book.children.all().order_by('parent_number')
116 extra_where = 'catalogue_tag.category = "theme"'
117 book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
118 extra_info = book.get_extra_info_value()
120 form = forms.SearchForm()
121 return render_to_response('catalogue/book_detail.html', locals(),
122 context_instance=RequestContext(request))
125 def book_text(request, slug):
126 book = get_object_or_404(models.Book, slug=slug)
128 for fragment in book.fragments.all():
129 for theme in fragment.tags.filter(category='theme'):
130 book_themes.setdefault(theme, []).append(fragment)
132 book_themes = book_themes.items()
133 book_themes.sort(key=lambda s: s[0].sort_key)
134 return render_to_response('catalogue/book_text.html', locals(),
135 context_instance=RequestContext(request))
141 def _tags_starting_with(prefix, user):
142 books = models.Book.objects.filter(title__icontains=prefix)
143 tags = models.Tag.objects.filter(name__icontains=prefix)
144 if user.is_authenticated():
145 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
147 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
149 return list(books) + list(tags)
153 tags = request.GET.get('tags', '')
154 prefix = request.GET.get('q', '')
155 # Prefix must have at least 2 characters
157 return HttpResponse('')
160 tag_list = models.Tag.get_tag_list(tags)
164 result = _tags_starting_with(prefix, request.user)
167 if isinstance(tag, models.Book):
168 return HttpResponseRedirect(tag.get_absolute_url())
172 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
173 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
177 def tags_starting_with(request):
178 prefix = request.GET.get('q', '')
179 # Prefix must have at least 2 characters
181 return HttpResponse('')
183 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
186 # ====================
187 # = Shelf management =
188 # ====================
191 def user_shelves(request):
192 shelves = models.Tag.objects.filter(category='set', user=request.user)
193 new_set_form = forms.NewSetForm()
194 return render_to_response('catalogue/user_shelves.html', locals(),
195 context_instance=RequestContext(request))
198 def book_sets(request, slug):
199 book = get_object_or_404(models.Book, slug=slug)
200 user_sets = models.Tag.objects.filter(category='set', user=request.user)
201 book_sets = book.tags.filter(category='set', user=request.user)
203 if not request.user.is_authenticated():
204 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
206 if request.method == 'POST':
207 form = forms.ObjectSetsForm(book, request.user, request.POST)
209 old_shelves = list(book.tags.filter(category='set'))
210 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
212 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
213 shelf.book_count -= 1
216 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
217 shelf.book_count += 1
220 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
221 if request.is_ajax():
222 return HttpResponse('<p>Półki zostały zapisane.</p>')
224 return HttpResponseRedirect('/')
226 form = forms.ObjectSetsForm(book, request.user)
227 new_set_form = forms.NewSetForm()
229 return render_to_response('catalogue/book_sets.html', locals(),
230 context_instance=RequestContext(request))
236 def remove_from_shelf(request, shelf, book):
237 book = get_object_or_404(models.Book, slug=book)
238 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
240 models.Tag.objects.remove_tag(book, shelf)
242 shelf.book_count -= 1
245 return HttpResponse('Usunieto')
249 def download_shelf(request, slug):
251 Create a ZIP archive on disk and transmit it in chunks of 8KB,
252 without loading the whole file into memory. A similar approach can
253 be used for large dynamic PDF files.
255 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
257 # Create a ZIP archive
258 temp = temp = tempfile.TemporaryFile()
259 archive = zipfile.ZipFile(temp, 'w')
261 # Collect all books to include in ZIP archive
262 def collect_books(books):
265 if len(book.children.all()) == 0:
268 result += collect_books(book.children.all())
271 for book in collect_books(models.Book.tagged.with_all(shelf)):
273 filename = book.pdf_file.path
274 archive.write(filename, str('%s.pdf' % book.slug))
276 filename = book.odt_file.path
277 archive.write(filename, str('%s.odt' % book.slug))
279 filename = book.txt_file.path
280 archive.write(filename, str('%s.txt' % book.slug))
283 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
284 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
285 response['Content-Length'] = temp.tell()
288 response.write(temp.read())
295 def new_set(request):
296 new_set_form = forms.NewSetForm(request.POST)
297 if new_set_form.is_valid():
298 new_set = new_set_form.save(request.user)
300 if request.is_ajax():
301 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
303 return HttpResponseRedirect('/')
305 return HttpResponseRedirect('/')
311 def delete_shelf(request, slug):
312 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
315 if request.is_ajax():
316 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
318 return HttpResponseRedirect('/')
327 form = AuthenticationForm(data=request.POST, prefix='login')
329 auth.login(request, form.get_user())
330 response_data = {'success': True, 'errors': {}}
332 response_data = {'success': False, 'errors': form.errors}
333 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
338 def register(request):
339 registration_form = UserCreationForm(request.POST, prefix='registration')
340 if registration_form.is_valid():
341 user = registration_form.save()
342 user = auth.authenticate(
343 username=registration_form.cleaned_data['username'],
344 password=registration_form.cleaned_data['password1']
346 auth.login(request, user)
347 response_data = {'success': True, 'errors': {}}
349 response_data = {'success': False, 'errors': registration_form.errors}
350 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
354 def logout_then_redirect(request):
356 return HttpResponseRedirect(request.GET.get('next', '/'))