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
19 from django.core.servers.basehttp import FileWrapper
21 from catalogue import models
22 from catalogue import forms
23 from catalogue.utils import split_tags
24 from newtagging import views as newtagging_views
27 class LazyEncoder(simplejson.JSONEncoder):
28 def default(self, obj):
29 if isinstance(obj, Promise):
30 return force_unicode(obj)
34 @cache.cache_control(must_revalidate=True, max_age=3600)
35 def main_page(request):
36 if request.user.is_authenticated():
37 shelves = models.Tag.objects.filter(category='set', user=request.user)
38 new_set_form = forms.NewSetForm()
39 extra_where = 'NOT catalogue_tag.category = "set"'
40 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
41 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
42 extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
43 categories = split_tags(tags)
45 form = forms.SearchForm()
46 return render_to_response('catalogue/main_page.html', locals(),
47 context_instance=RequestContext(request))
50 def book_list(request):
51 books = models.Book.objects.all()
52 form = forms.SearchForm()
54 books_by_first_letter = SortedDict()
56 books_by_first_letter.setdefault(book.title[0], []).append(book)
58 return render_to_response('catalogue/book_list.html', locals(),
59 context_instance=RequestContext(request))
62 @cache.cache_control(must_revalidate=True, max_age=3600)
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:
74 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
75 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
77 model = models.Fragment
79 extra_where = 'NOT catalogue_tag.category = "set"'
80 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
81 categories = split_tags(related_tags)
84 model=models.Book.objects.filter(parent=None)
86 return newtagging_views.tagged_object_list(
89 queryset_or_model=model,
91 template_name='catalogue/tagged_object_list.html',
92 extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set },
96 def book_detail(request, slug):
97 book = get_object_or_404(models.Book, slug=slug)
98 tags = list(book.tags.filter(~Q(category='set')))
99 categories = split_tags(tags)
100 book_children = book.children.all().order_by('parent_number')
102 form = forms.SearchForm()
103 return render_to_response('catalogue/book_detail.html', locals(),
104 context_instance=RequestContext(request))
107 def book_text(request, slug):
108 book = get_object_or_404(models.Book, slug=slug)
110 for fragment in book.fragments.all():
111 for theme in fragment.tags.filter(category='theme'):
112 book_themes.setdefault(theme, []).append(fragment)
114 book_themes = book_themes.items()
115 book_themes.sort(key=lambda s: s[0].sort_key)
116 return render_to_response('catalogue/book_text.html', locals(),
117 context_instance=RequestContext(request))
124 query = request.GET.get('q', '')
125 tags = request.GET.get('tags', '')
130 tag_list = models.Tag.get_tag_list(tags)
131 tag = models.Tag.objects.get(name=query)
132 except models.Tag.DoesNotExist:
134 book = models.Book.objects.get(title=query)
135 return HttpResponseRedirect(book.get_absolute_url())
136 except models.Book.DoesNotExist:
137 return HttpResponseRedirect(reverse('catalogue.views.main_page'))
140 return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list',
141 kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
145 def tags_starting_with(request):
147 prefix = request.GET['q']
151 books = models.Book.objects.filter(title__icontains=prefix)
152 tags = models.Tag.objects.filter(name__icontains=prefix)
153 if request.user.is_authenticated():
154 tags = tags.filter(~Q(category='set') | Q(user=request.user))
156 tags = tags.filter(~Q(category='set'))
158 completions = [book.title for book in books] + [tag.name for tag in tags]
160 return HttpResponse('\n'.join(completions))
163 return HttpResponse('')
166 # ====================
167 # = Shelf management =
168 # ====================
171 def user_shelves(request):
172 shelves = models.Tag.objects.filter(category='set', user=request.user)
173 new_set_form = forms.NewSetForm()
174 return render_to_response('catalogue/user_shelves.html', locals(),
175 context_instance=RequestContext(request))
179 def book_sets(request, slug):
180 book = get_object_or_404(models.Book, slug=slug)
181 user_sets = models.Tag.objects.filter(category='set', user=request.user)
182 book_sets = book.tags.filter(category='set', user=request.user)
184 if not request.user.is_authenticated():
185 return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
187 if request.method == 'POST':
188 form = forms.ObjectSetsForm(book, request.user, request.POST)
190 book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
191 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
192 if request.is_ajax():
193 return HttpResponse('<p>Półki zostały zapisane.</p>')
195 return HttpResponseRedirect('/')
197 form = forms.ObjectSetsForm(book, request.user)
198 new_set_form = forms.NewSetForm()
200 return render_to_response('catalogue/book_sets.html', locals(),
201 context_instance=RequestContext(request))
205 def download_shelf(request, slug):
207 Create a ZIP archive on disk and transmit it in chunks of 8KB,
208 without loading the whole file into memory. A similar approach can
209 be used for large dynamic PDF files.
211 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
213 # Create a ZIP archive
214 temp = temp = tempfile.TemporaryFile()
215 archive = zipfile.ZipFile(temp, 'w')
216 for book in models.Book.tagged.with_all(shelf):
218 filename = book.pdf_file.path
219 archive.write(filename, str('%s.pdf' % book.slug))
221 filename = book.odt_file.path
222 archive.write(filename, str('%s.odt' % book.slug))
224 filename = book.txt_file.path
225 archive.write(filename, str('%s.txt' % book.slug))
228 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
229 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
230 response['Content-Length'] = temp.tell()
233 response.write(temp.read())
240 def new_set(request):
241 new_set_form = forms.NewSetForm(request.POST)
242 if new_set_form.is_valid():
243 new_set = new_set_form.save(request.user)
245 if request.is_ajax():
246 return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
248 return HttpResponseRedirect('/')
250 return render_to_response('catalogue/book_sets.html', locals(),
251 context_instance=RequestContext(request))
257 def delete_shelf(request, slug):
258 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
261 if request.is_ajax():
262 return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
264 return HttpResponseRedirect('/')
273 form = AuthenticationForm(data=request.POST, prefix='login')
275 auth.login(request, form.get_user())
276 response_data = {'success': True, 'errors': {}}
278 response_data = {'success': False, 'errors': form.errors}
279 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
284 def register(request):
285 registration_form = UserCreationForm(request.POST, prefix='registration')
286 if registration_form.is_valid():
287 user = registration_form.save()
288 user = auth.authenticate(
289 username=registration_form.cleaned_data['username'],
290 password=registration_form.cleaned_data['password1']
292 auth.login(request, user)
293 response_data = {'success': True, 'errors': {}}
295 response_data = {'success': False, 'errors': registration_form.errors}
296 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
300 def logout_then_redirect(request):
302 return HttpResponseRedirect(request.GET.get('next', '/'))