Wypisywanie błędów przy importowaniu książek (obecnie wypisujemy po prostu wyjątek...
[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 = {'categories': categories, 'shelf_is_set': shelf_is_set, 'user_is_owner': user_is_owner },
102     )
103
104
105 def book_fragments(request, book_slug, theme_slug):
106     book = get_object_or_404(models.Book, slug=book_slug)
107     book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
108     theme = get_object_or_404(models.Tag, slug=theme_slug)
109     fragments = models.Fragment.tagged.with_all([book_tag, theme])
110     
111     form = forms.SearchForm()
112     return render_to_response('catalogue/book_fragments.html', locals(),
113         context_instance=RequestContext(request))
114
115
116 def book_detail(request, slug):
117     book = get_object_or_404(models.Book, slug=slug)
118     book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
119     tags = list(book.tags.filter(~Q(category='set')))
120     categories = split_tags(tags)
121     book_children = book.children.all().order_by('parent_number')
122     extra_where = 'catalogue_tag.category = "theme"'
123     book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
124     extra_info = book.get_extra_info_value()
125     
126     form = forms.SearchForm()
127     return render_to_response('catalogue/book_detail.html', locals(),
128         context_instance=RequestContext(request))
129
130
131 def book_text(request, slug):
132     book = get_object_or_404(models.Book, slug=slug)
133     book_themes = {}
134     for fragment in book.fragments.all():
135         for theme in fragment.tags.filter(category='theme'):
136             book_themes.setdefault(theme, []).append(fragment)
137     
138     book_themes = book_themes.items()
139     book_themes.sort(key=lambda s: s[0].sort_key)
140     return render_to_response('catalogue/book_text.html', locals(),
141         context_instance=RequestContext(request))
142
143
144 # ==========
145 # = Search =
146 # ==========
147 def _tags_starting_with(prefix, user):
148     books = models.Book.objects.filter(title__icontains=prefix)
149     tags = models.Tag.objects.filter(name__icontains=prefix)
150     if user.is_authenticated():
151         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
152     else:
153         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
154
155     return list(books) + list(tags)
156         
157
158 def search(request):
159     tags = request.GET.get('tags', '')
160     prefix = request.GET.get('q', '')
161     # Prefix must have at least 2 characters
162     if len(prefix) < 2:
163         return HttpResponse('')
164     
165     try:
166         tag_list = models.Tag.get_tag_list(tags)
167     except:
168         tag_list = []
169     
170     result = _tags_starting_with(prefix, request.user)
171     if len(result) > 0:
172         tag = result[0]
173         if isinstance(tag, models.Book):
174             return HttpResponseRedirect(tag.get_absolute_url())
175         else:
176             tag_list.append(tag)
177         
178     return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list', 
179         kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
180     ))
181
182
183 def tags_starting_with(request):
184     prefix = request.GET.get('q', '')
185     # Prefix must have at least 2 characters
186     if len(prefix) < 2:
187         return HttpResponse('')
188     
189     return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
190
191
192 # ====================
193 # = Shelf management =
194 # ====================
195 @login_required
196 @cache.never_cache
197 def user_shelves(request):
198     shelves = models.Tag.objects.filter(category='set', user=request.user)
199     new_set_form = forms.NewSetForm()
200     return render_to_response('catalogue/user_shelves.html', locals(),
201             context_instance=RequestContext(request))
202
203 @cache.never_cache
204 def book_sets(request, slug):
205     book = get_object_or_404(models.Book, slug=slug)
206     user_sets = models.Tag.objects.filter(category='set', user=request.user)
207     book_sets = book.tags.filter(category='set', user=request.user)
208     
209     if not request.user.is_authenticated():
210         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
211     
212     if request.method == 'POST':
213         form = forms.ObjectSetsForm(book, request.user, request.POST)
214         if form.is_valid():
215             old_shelves = list(book.tags.filter(category='set'))
216             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
217             
218             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
219                 shelf.book_count -= 1
220                 shelf.save()
221                 
222             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
223                 shelf.book_count += 1
224                 shelf.save()
225             
226             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
227             if request.is_ajax():
228                 return HttpResponse('<p>Półki zostały zapisane.</p>')
229             else:
230                 return HttpResponseRedirect('/')
231     else:
232         form = forms.ObjectSetsForm(book, request.user)
233         new_set_form = forms.NewSetForm()
234     
235     return render_to_response('catalogue/book_sets.html', locals(),
236         context_instance=RequestContext(request))
237
238
239 @login_required
240 @require_POST
241 @cache.never_cache
242 def remove_from_shelf(request, shelf, book):
243     book = get_object_or_404(models.Book, slug=book)
244     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
245     
246     models.Tag.objects.remove_tag(book, shelf)
247     
248     shelf.book_count -= 1
249     shelf.save()
250     
251     return HttpResponse('Usunieto')
252
253
254 @cache.never_cache
255 def download_shelf(request, slug):
256     """"
257     Create a ZIP archive on disk and transmit it in chunks of 8KB,
258     without loading the whole file into memory. A similar approach can
259     be used for large dynamic PDF files.                                        
260     """
261     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
262             
263     # Create a ZIP archive
264     temp = temp = tempfile.TemporaryFile()
265     archive = zipfile.ZipFile(temp, 'w')
266     
267     # Collect all books to include in ZIP archive
268     def collect_books(books):
269         result = []
270         for book in books:
271             if len(book.children.all()) == 0:
272                 result.append(book)
273             else:
274                 result += collect_books(book.children.all())
275         return result
276     
277     for book in collect_books(models.Book.tagged.with_all(shelf)):
278         if book.pdf_file:
279             filename = book.pdf_file.path
280             archive.write(filename, str('%s.pdf' % book.slug))
281         if book.odt_file:
282             filename = book.odt_file.path
283             archive.write(filename, str('%s.odt' % book.slug))
284         if book.txt_file:
285             filename = book.txt_file.path
286             archive.write(filename, str('%s.txt' % book.slug))
287     archive.close()
288     
289     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
290     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
291     response['Content-Length'] = temp.tell()
292     
293     temp.seek(0)
294     response.write(temp.read())
295     return response
296
297
298 @login_required
299 @require_POST
300 @cache.never_cache
301 def new_set(request):
302     new_set_form = forms.NewSetForm(request.POST)
303     if new_set_form.is_valid():
304         new_set = new_set_form.save(request.user)
305
306         if request.is_ajax():
307             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
308         else:
309             return HttpResponseRedirect('/')
310
311     return HttpResponseRedirect('/')
312
313
314 @login_required
315 @require_POST
316 @cache.never_cache
317 def delete_shelf(request, slug):
318     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
319     user_set.delete()
320
321     if request.is_ajax():
322         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
323     else:
324         return HttpResponseRedirect('/')
325
326
327 # ==================
328 # = Authentication =
329 # ==================
330 @require_POST
331 @cache.never_cache
332 def login(request):
333     form = AuthenticationForm(data=request.POST, prefix='login')
334     if form.is_valid():
335         auth.login(request, form.get_user())
336         response_data = {'success': True, 'errors': {}}
337     else:
338         response_data = {'success': False, 'errors': form.errors}
339     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
340
341
342 @require_POST
343 @cache.never_cache
344 def register(request):
345     registration_form = UserCreationForm(request.POST, prefix='registration')
346     if registration_form.is_valid():
347         user = registration_form.save()
348         user = auth.authenticate(
349             username=registration_form.cleaned_data['username'], 
350             password=registration_form.cleaned_data['password1']
351         )
352         auth.login(request, user)
353         response_data = {'success': True, 'errors': {}}
354     else:
355         response_data = {'success': False, 'errors': registration_form.errors}
356     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
357
358
359 @cache.never_cache
360 def logout_then_redirect(request):
361     auth.logout(request)
362     return HttpResponseRedirect(request.GET.get('next', '/'))
363
364
365
366 # =========
367 # = Admin =
368 # =========
369 @login_required
370 @staff_required
371 def import_book(request):
372     """docstring for import_book"""
373     book_import_form = forms.BookImportForm(request.POST, request.FILES)
374     if book_import_form.is_valid():
375         try:
376             book_import_form.save()
377         except:
378             info = sys.exc_info()
379             exception = pprint.pformat(info[1])
380             tb = '\n'.join(traceback.format_tb(info[2]))
381             return HttpResponse("An error occurred: %s\n\n%s" % (exception, tb), mimetype='text/plain')
382         return HttpResponse("Book imported successfully")
383     else:
384         return HttpResponse("Error importing file: %r" % book_import_form.errors)