a0315a4c6feb09a6d1948c787ca36214486d14f2
[wolnelektury.git] / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 from django.template import RequestContext
3 from django.shortcuts import render_to_response, get_object_or_404
4 from django.http import HttpResponse, HttpResponseRedirect, Http404
5 from django.core.urlresolvers import reverse
6 from django.db.models import Q
7 from django.contrib.auth.decorators import login_required
8 from django.utils.datastructures import SortedDict
9 from django.views.decorators.http import require_POST
10
11 from catalogue import models
12 from catalogue import forms
13 from catalogue.utils import split_tags
14
15
16 def catalogue_redirect(request, tags=''):
17     if len(request.GET['q']) > 0:
18         try:
19             tag = models.Tag.objects.get(name=request.GET['q'])
20             if len(tags):
21                 tags += '/'
22             tags = tags + tag.slug
23         except models.Tag.DoesNotExist:
24             book = get_object_or_404(models.Book, title=request.GET['q'])
25             return HttpResponseRedirect(book.get_absolute_url())
26     if len(tags) > 0:
27         return HttpResponseRedirect(reverse('catalogue.views.tagged_book_list', kwargs=dict(tags=tags)))
28     else:
29         return HttpResponseRedirect(reverse('catalogue.views.main_page'))
30
31
32 def tags_starting_with(request):
33     try:
34         prefix = request.GET['q']
35         if len(prefix) < 2:
36             raise KeyError
37             
38         books = models.Book.objects.filter(title__icontains=prefix)
39         tags = models.Tag.objects.filter(name__icontains=prefix)
40         if request.user.is_authenticated():
41             tags = tags.filter(~Q(category='set') | Q(user=request.user))
42         else:
43             tags = tags.filter(~Q(category='set'))
44         
45         completions = [book.title for book in books] + [tag.name for tag in tags]
46
47         return HttpResponse('\n'.join(completions))    
48     
49     except KeyError:
50         return HttpResponse('')
51
52
53 def main_page(request):
54     if 'q' in request.GET:
55         return catalogue_redirect(request)
56     
57     if request.user.is_authenticated():
58         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
59     else:
60         extra_where = 'NOT catalogue_tag.category = "set"'
61     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
62     categories = split_tags(tags)
63     
64     form = forms.SearchForm()
65     return render_to_response('catalogue/main_page.html', locals(),
66         context_instance=RequestContext(request))
67
68
69 def book_list(request):
70     if 'q' in request.GET:
71         return catalogue_redirect(request)
72         
73     books = models.Book.objects.all()
74     form = forms.SearchForm()
75     
76     books_by_first_letter = SortedDict()
77     for book in books:
78         books_by_first_letter.setdefault(book.title[0], []).append(book)
79     
80     return render_to_response('catalogue/book_list.html', locals(),
81         context_instance=RequestContext(request))
82
83
84 def tagged_book_list(request, tags=''):
85     if 'q' in request.GET:
86         return catalogue_redirect(request, tags)
87     
88     choices_split = tags.split('/')
89     tags = []
90     for tag in choices_split:
91         tag = get_object_or_404(models.Tag, slug=tag)
92         if tag.category == 'set' and (not request.user.is_authenticated() or request.user != tag.user):
93             raise Http404
94         tags.append(tag)
95         
96     books = models.Book.objects.with_all(tags)
97     
98     if request.user.is_authenticated():
99         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
100     else:
101         extra_where = 'NOT catalogue_tag.category = "set"'
102     related_tags = models.Tag.objects.related_for_model(tags, models.Book, counts=True, extra={'where': [extra_where]})
103     categories = split_tags(related_tags)
104     
105     form = forms.SearchForm()
106     
107     return render_to_response('catalogue/tagged_book_list.html', dict(
108         tags=tags,
109         form=form,
110         books=books,
111         categories=categories,
112     ), context_instance=RequestContext(request))
113
114
115 def book_detail(request, slug):
116     book = get_object_or_404(models.Book, slug=slug)
117     tags = list(book.tags.filter(~Q(category='set')))
118     categories = split_tags(tags)
119     search_form = forms.SearchForm()
120     
121     return render_to_response('catalogue/book_detail.html', locals(),
122         context_instance=RequestContext(request))
123
124
125 @login_required
126 def book_sets(request, slug):
127     book = get_object_or_404(models.Book, slug=slug)
128     user_sets = models.Tag.objects.filter(category='set', user=request.user)
129     book_sets = book.tags.filter(category='set', user=request.user)
130     
131     if request.method == 'POST':
132         form = forms.BookSetsForm(book, request.user, request.POST)
133         if form.is_valid():
134             book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
135                 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
136             if request.is_ajax():
137                 return HttpResponse('<p>Zestawy zostały zapisane</p>')
138             else:
139                 return HttpResponseRedirect('/')
140     else:
141         form = forms.BookSetsForm(book, request.user)
142         new_set_form = forms.NewSetForm()
143     
144     return render_to_response('catalogue/book_sets.html', locals(),
145         context_instance=RequestContext(request))
146
147 @login_required
148 @require_POST
149 def new_set(request):
150     new_set_form = forms.NewSetForm(request.POST)
151     if new_set_form.is_valid():
152         new_set = new_set_form.save(request.user)
153         return HttpResponse('<p>Zestaw <strong>%s</strong> został utworzony</p>' % new_set)
154     
155     return render_to_response('catalogue/book_sets.html', locals(),
156             context_instance=RequestContext(request))
157