Added tag wolnelektury-0.9.1 for changeset fed64f1e09c1
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 import tempfile
3 import zipfile
4
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
20
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
25
26
27 class LazyEncoder(simplejson.JSONEncoder):
28     def default(self, obj):
29         if isinstance(obj, Promise):
30             return force_unicode(obj)
31         return obj
32
33
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)
44     
45     form = forms.SearchForm()
46     return render_to_response('catalogue/main_page.html', locals(),
47         context_instance=RequestContext(request))
48
49
50 def book_list(request):
51     books = models.Book.objects.all()
52     form = forms.SearchForm()
53     
54     books_by_first_letter = SortedDict()
55     for book in books:
56         books_by_first_letter.setdefault(book.title[0], []).append(book)
57     
58     return render_to_response('catalogue/book_list.html', locals(),
59         context_instance=RequestContext(request))
60
61
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:
66         raise Http404
67         
68     try:
69         tags = models.Tag.get_tag_list(tags)
70     except models.Tag.DoesNotExist:
71         raise Http404
72     
73     model = models.Book
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
76     if theme_is_set:
77         model = models.Fragment
78
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)
82
83     if not theme_is_set:
84         model=models.Book.objects.filter(parent=None)
85     
86     return newtagging_views.tagged_object_list(
87         request,
88         tag_model=models.Tag,
89         queryset_or_model=model,
90         tags=tags,
91         template_name='catalogue/tagged_object_list.html',
92         extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set },
93     )
94
95
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')
101     
102     form = forms.SearchForm()
103     return render_to_response('catalogue/book_detail.html', locals(),
104         context_instance=RequestContext(request))
105
106
107 def book_text(request, slug):
108     book = get_object_or_404(models.Book, slug=slug)
109     book_themes = {}
110     for fragment in book.fragments.all():
111         for theme in fragment.tags.filter(category='theme'):
112             book_themes.setdefault(theme, []).append(fragment)
113     
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))
118
119
120 # ==========
121 # = Search =
122 # ==========
123 def search(request):
124     query = request.GET.get('q', '')
125     tags = request.GET.get('tags', '')
126     if tags == '':
127         tags = []
128
129     try:
130         tag_list = models.Tag.get_tag_list(tags)
131         tag = models.Tag.objects.get(name=query)
132     except models.Tag.DoesNotExist:
133         try:
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'))
138     else:
139         tag_list.append(tag)
140         return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list', 
141             kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
142         ))
143
144
145 def tags_starting_with(request):
146     try:
147         prefix = request.GET['q']
148         if len(prefix) < 2:
149             raise KeyError
150
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))
155         else:
156             tags = tags.filter(~Q(category='set'))
157
158         completions = [book.title for book in books] + [tag.name for tag in tags]
159
160         return HttpResponse('\n'.join(completions))    
161
162     except KeyError:
163         return HttpResponse('')
164
165
166 # ====================
167 # = Shelf management =
168 # ====================
169 @login_required
170 @cache.never_cache
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))
176
177
178 @cache.never_cache
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)
183     
184     if not request.user.is_authenticated():
185         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
186     
187     if request.method == 'POST':
188         form = forms.ObjectSetsForm(book, request.user, request.POST)
189         if form.is_valid():
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>')
194             else:
195                 return HttpResponseRedirect('/')
196     else:
197         form = forms.ObjectSetsForm(book, request.user)
198         new_set_form = forms.NewSetForm()
199     
200     return render_to_response('catalogue/book_sets.html', locals(),
201         context_instance=RequestContext(request))
202
203
204 @cache.never_cache
205 def download_shelf(request, slug):
206     """"
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.                                        
210     """
211     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
212             
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):
217         if book.pdf_file:
218             filename = book.pdf_file.path
219             archive.write(filename, str('%s.pdf' % book.slug))
220         if book.odt_file:
221             filename = book.odt_file.path
222             archive.write(filename, str('%s.odt' % book.slug))
223         if book.txt_file:
224             filename = book.txt_file.path
225             archive.write(filename, str('%s.txt' % book.slug))
226     archive.close()
227     
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()
231     
232     temp.seek(0)
233     response.write(temp.read())
234     return response
235
236
237 @login_required
238 @require_POST
239 @cache.never_cache
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)
244
245         if request.is_ajax():
246             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
247         else:
248             return HttpResponseRedirect('/')
249
250     return render_to_response('catalogue/book_sets.html', locals(),
251             context_instance=RequestContext(request))
252
253
254 @login_required
255 @require_POST
256 @cache.never_cache
257 def delete_shelf(request, slug):
258     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
259     user_set.delete()
260
261     if request.is_ajax():
262         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
263     else:
264         return HttpResponseRedirect('/')
265
266
267 # ==================
268 # = Authentication =
269 # ==================
270 @require_POST
271 @cache.never_cache
272 def login(request):
273     form = AuthenticationForm(data=request.POST, prefix='login')
274     if form.is_valid():
275         auth.login(request, form.get_user())
276         response_data = {'success': True, 'errors': {}}
277     else:
278         response_data = {'success': False, 'errors': form.errors}
279     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
280
281
282 @require_POST
283 @cache.never_cache
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']
291         )
292         auth.login(request, user)
293         response_data = {'success': True, 'errors': {}}
294     else:
295         response_data = {'success': False, 'errors': registration_form.errors}
296     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
297
298
299 @cache.never_cache
300 def logout_then_redirect(request):
301     auth.logout(request)
302     return HttpResponseRedirect(request.GET.get('next', '/'))
303