Dodanie tekstów do bannera 1% na potrzeby wystąpienia w Wiadomościach Polsatu.
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 import tempfile
3 import zipfile
4 import sys
5 import pprint
6 import traceback
7
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
22
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
27
28
29 staff_required = user_passes_test(lambda user: user.is_staff)
30
31
32 class LazyEncoder(simplejson.JSONEncoder):
33     def default(self, obj):
34         if isinstance(obj, Promise):
35             return force_unicode(obj)
36         return obj
37
38
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)
48     
49     form = forms.SearchForm()
50     return render_to_response('catalogue/main_page.html', locals(),
51         context_instance=RequestContext(request))
52
53
54 def book_list(request):
55     books = models.Book.objects.all()
56     form = forms.SearchForm()
57     
58     books_by_first_letter = SortedDict()
59     for book in books:
60         books_by_first_letter.setdefault(book.title[0], []).append(book)
61     
62     return render_to_response('catalogue/book_list.html', locals(),
63         context_instance=RequestContext(request))
64
65
66 def tagged_object_list(request, tags=''):
67     # Prevent DoS attacks on our database
68     if len(tags.split('/')) > 6:
69         raise Http404
70         
71     try:
72         tags = models.Tag.get_tag_list(tags)
73     except models.Tag.DoesNotExist:
74         raise Http404
75     
76     if len([tag for tag in tags if tag.category == 'book']):
77         raise Http404
78     
79     model = models.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
83     if theme_is_set:
84         model = models.Fragment
85
86     user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
87     
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)
91
92     if not (theme_is_set or shelf_is_set):
93         model=models.Book.objects.filter(parent=None)
94     
95     return newtagging_views.tagged_object_list(
96         request,
97         tag_model=models.Tag,
98         queryset_or_model=model,
99         tags=tags,
100         template_name='catalogue/tagged_object_list.html',
101         extra_context = {
102             'categories': categories,
103             'shelf_is_set': shelf_is_set,
104             'user_is_owner': user_is_owner,
105             'formats_form': forms.DownloadFormatsForm(),
106         },
107     )
108
109
110 def book_fragments(request, book_slug, theme_slug):
111     book = get_object_or_404(models.Book, slug=book_slug)
112     book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
113     theme = get_object_or_404(models.Tag, slug=theme_slug)
114     fragments = models.Fragment.tagged.with_all([book_tag, theme])
115     
116     form = forms.SearchForm()
117     return render_to_response('catalogue/book_fragments.html', locals(),
118         context_instance=RequestContext(request))
119
120
121 def book_detail(request, slug):
122     book = get_object_or_404(models.Book, slug=slug)
123     book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
124     tags = list(book.tags.filter(~Q(category='set')))
125     categories = split_tags(tags)
126     book_children = book.children.all().order_by('parent_number')
127     extra_where = 'catalogue_tag.category = "theme"'
128     book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
129     extra_info = book.get_extra_info_value()
130     
131     form = forms.SearchForm()
132     return render_to_response('catalogue/book_detail.html', locals(),
133         context_instance=RequestContext(request))
134
135
136 def book_text(request, slug):
137     book = get_object_or_404(models.Book, slug=slug)
138     book_themes = {}
139     for fragment in book.fragments.all():
140         for theme in fragment.tags.filter(category='theme'):
141             book_themes.setdefault(theme, []).append(fragment)
142     
143     book_themes = book_themes.items()
144     book_themes.sort(key=lambda s: s[0].sort_key)
145     return render_to_response('catalogue/book_text.html', locals(),
146         context_instance=RequestContext(request))
147
148
149 # ==========
150 # = Search =
151 # ==========
152 def _tags_starting_with(prefix, user):
153     books = models.Book.objects.filter(title__icontains=prefix)
154     tags = models.Tag.objects.filter(name__icontains=prefix)
155     if user.is_authenticated():
156         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
157     else:
158         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
159
160     return list(books) + list(tags)
161         
162
163 def search(request):
164     tags = request.GET.get('tags', '')
165     prefix = request.GET.get('q', '')
166     # Prefix must have at least 2 characters
167     if len(prefix) < 2:
168         return HttpResponse('')
169     
170     try:
171         tag_list = models.Tag.get_tag_list(tags)
172     except:
173         tag_list = []
174     
175     result = _tags_starting_with(prefix, request.user)
176     if len(result) > 0:
177         tag = result[0]
178         if isinstance(tag, models.Book):
179             return HttpResponseRedirect(tag.get_absolute_url())
180         else:
181             tag_list.append(tag)
182         
183     return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list', 
184         kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
185     ))
186
187
188 def tags_starting_with(request):
189     prefix = request.GET.get('q', '')
190     # Prefix must have at least 2 characters
191     if len(prefix) < 2:
192         return HttpResponse('')
193     
194     return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
195
196
197 # ====================
198 # = Shelf management =
199 # ====================
200 @login_required
201 @cache.never_cache
202 def user_shelves(request):
203     shelves = models.Tag.objects.filter(category='set', user=request.user)
204     new_set_form = forms.NewSetForm()
205     return render_to_response('catalogue/user_shelves.html', locals(),
206             context_instance=RequestContext(request))
207
208 @cache.never_cache
209 def book_sets(request, slug):
210     book = get_object_or_404(models.Book, slug=slug)
211     user_sets = models.Tag.objects.filter(category='set', user=request.user)
212     book_sets = book.tags.filter(category='set', user=request.user)
213     
214     if not request.user.is_authenticated():
215         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
216     
217     if request.method == 'POST':
218         form = forms.ObjectSetsForm(book, request.user, request.POST)
219         if form.is_valid():
220             old_shelves = list(book.tags.filter(category='set'))
221             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
222             
223             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
224                 shelf.book_count -= 1
225                 shelf.save()
226                 
227             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
228                 shelf.book_count += 1
229                 shelf.save()
230             
231             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
232             if request.is_ajax():
233                 return HttpResponse('<p>Półki zostały zapisane.</p>')
234             else:
235                 return HttpResponseRedirect('/')
236     else:
237         form = forms.ObjectSetsForm(book, request.user)
238         new_set_form = forms.NewSetForm()
239     
240     return render_to_response('catalogue/book_sets.html', locals(),
241         context_instance=RequestContext(request))
242
243
244 @login_required
245 @require_POST
246 @cache.never_cache
247 def remove_from_shelf(request, shelf, book):
248     book = get_object_or_404(models.Book, slug=book)
249     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
250     
251     models.Tag.objects.remove_tag(book, shelf)
252     
253     shelf.book_count -= 1
254     shelf.save()
255     
256     return HttpResponse('Usunieto')
257
258
259 def collect_books(books):
260     """
261     Returns all real books in collection.
262     """
263     result = []
264     for book in books:
265         if len(book.children.all()) == 0:
266             result.append(book)
267         else:
268             result += collect_books(book.children.all())
269     return result
270
271
272 @cache.never_cache
273 def download_shelf(request, slug):
274     """"
275     Create a ZIP archive on disk and transmit it in chunks of 8KB,
276     without loading the whole file into memory. A similar approach can
277     be used for large dynamic PDF files.                                        
278     """
279     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
280     
281     formats = []
282     form = forms.DownloadFormatsForm(request.GET)
283     if form.is_valid():
284         formats = form.cleaned_data['formats']
285     if len(formats) == 0:
286         formats = ['pdf', 'odt', 'txt', 'mp3', 'ogg']
287     
288     # Create a ZIP archive
289     temp = temp = tempfile.TemporaryFile()
290     archive = zipfile.ZipFile(temp, 'w')
291     
292     for book in collect_books(models.Book.tagged.with_all(shelf)):
293         if 'pdf' in formats and book.pdf_file:
294             filename = book.pdf_file.path
295             archive.write(filename, str('%s.pdf' % book.slug))
296         if 'odt' in formats and book.odt_file:
297             filename = book.odt_file.path
298             archive.write(filename, str('%s.odt' % book.slug))
299         if 'txt' in formats and book.txt_file:
300             filename = book.txt_file.path
301             archive.write(filename, str('%s.txt' % book.slug))
302         if 'mp3' in formats and book.mp3_file:
303             filename = book.mp3_file.path
304             archive.write(filename, str('%s.mp3' % book.slug))
305         if 'ogg' in formats and book.ogg_file:
306             filename = book.ogg_file.path
307             archive.write(filename, str('%s.ogg' % book.slug))
308     archive.close()
309     
310     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
311     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
312     response['Content-Length'] = temp.tell()
313     
314     temp.seek(0)
315     response.write(temp.read())
316     return response
317
318
319 @cache.never_cache
320 def shelf_book_formats(request, shelf):
321     """"
322     Returns a list of formats of books in shelf.
323     """
324     shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
325
326     formats = {'pdf': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
327     
328     for book in collect_books(models.Book.tagged.with_all(shelf)):
329         if book.pdf_file:
330             formats['pdf'] = True
331         if book.odt_file:
332             formats['odt'] = True
333         if book.txt_file:
334             formats['txt'] = True
335         if book.mp3_file:
336             formats['mp3'] = True
337         if book.ogg_file:
338             formats['ogg'] = True
339
340     return HttpResponse(LazyEncoder().encode(formats))
341
342
343 @login_required
344 @require_POST
345 @cache.never_cache
346 def new_set(request):
347     new_set_form = forms.NewSetForm(request.POST)
348     if new_set_form.is_valid():
349         new_set = new_set_form.save(request.user)
350
351         if request.is_ajax():
352             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
353         else:
354             return HttpResponseRedirect('/')
355
356     return HttpResponseRedirect('/')
357
358
359 @login_required
360 @require_POST
361 @cache.never_cache
362 def delete_shelf(request, slug):
363     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
364     user_set.delete()
365
366     if request.is_ajax():
367         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
368     else:
369         return HttpResponseRedirect('/')
370
371
372 # ==================
373 # = Authentication =
374 # ==================
375 @require_POST
376 @cache.never_cache
377 def login(request):
378     form = AuthenticationForm(data=request.POST, prefix='login')
379     if form.is_valid():
380         auth.login(request, form.get_user())
381         response_data = {'success': True, 'errors': {}}
382     else:
383         response_data = {'success': False, 'errors': form.errors}
384     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
385
386
387 @require_POST
388 @cache.never_cache
389 def register(request):
390     registration_form = UserCreationForm(request.POST, prefix='registration')
391     if registration_form.is_valid():
392         user = registration_form.save()
393         user = auth.authenticate(
394             username=registration_form.cleaned_data['username'], 
395             password=registration_form.cleaned_data['password1']
396         )
397         auth.login(request, user)
398         response_data = {'success': True, 'errors': {}}
399     else:
400         response_data = {'success': False, 'errors': registration_form.errors}
401     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
402
403
404 @cache.never_cache
405 def logout_then_redirect(request):
406     auth.logout(request)
407     return HttpResponseRedirect(request.GET.get('next', '/'))
408
409
410
411 # =========
412 # = Admin =
413 # =========
414 @login_required
415 @staff_required
416 def import_book(request):
417     """docstring for import_book"""
418     book_import_form = forms.BookImportForm(request.POST, request.FILES)
419     if book_import_form.is_valid():
420         try:
421             book_import_form.save()
422         except:
423             info = sys.exc_info()
424             exception = pprint.pformat(info[1])
425             tb = '\n'.join(traceback.format_tb(info[2]))
426             return HttpResponse("An error occurred: %s\n\n%s" % (exception, tb), mimetype='text/plain')
427         return HttpResponse("Book imported successfully")
428     else:
429         return HttpResponse("Error importing file: %r" % book_import_form.errors)