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