dc2e7b107de60fc502e192ba8511b8f25cb8003b
[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_GET, 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 # @require_GET
33 # def tag_search(request):
34 #     search_form = forms.SearchForm(request.GET)
35 #     if search_form.is_valid():
36 #         query = search_form.cleaned_data['q']
37 #         tags = search_form.cleaned_data['tags']
38 #         
39     
40     
41 def tags_starting_with(request):
42     try:
43         prefix = request.GET['q']
44         if len(prefix) < 2:
45             raise KeyError
46             
47         books = models.Book.objects.filter(title__icontains=prefix)
48         tags = models.Tag.objects.filter(name__icontains=prefix)
49         if request.user.is_authenticated():
50             tags = tags.filter(~Q(category='set') | Q(user=request.user))
51         else:
52             tags = tags.filter(~Q(category='set'))
53         
54         completions = [book.title for book in books] + [tag.name for tag in tags]
55
56         return HttpResponse('\n'.join(completions))    
57     
58     except KeyError:
59         return HttpResponse('')
60
61
62 def main_page(request):
63     if 'q' in request.GET:
64         return catalogue_redirect(request)
65     
66     if request.user.is_authenticated():
67         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
68     else:
69         extra_where = 'NOT catalogue_tag.category = "set"'
70     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
71     categories = split_tags(tags)
72     
73     form = forms.SearchForm()
74     return render_to_response('catalogue/main_page.html', locals(),
75         context_instance=RequestContext(request))
76
77
78 def book_list(request):
79     if 'q' in request.GET:
80         return catalogue_redirect(request)
81         
82     books = models.Book.objects.all()
83     form = forms.SearchForm()
84     
85     books_by_first_letter = SortedDict()
86     for book in books:
87         books_by_first_letter.setdefault(book.title[0], []).append(book)
88     
89     return render_to_response('catalogue/book_list.html', locals(),
90         context_instance=RequestContext(request))
91
92
93 def tagged_book_list(request, tags=''):
94     if 'q' in request.GET:
95         return catalogue_redirect(request, tags)
96     
97     choices_split = tags.split('/')
98     tags = []
99     for tag in choices_split:
100         tag = get_object_or_404(models.Tag, slug=tag)
101         if tag.category == 'set' and (not request.user.is_authenticated() or request.user != tag.user):
102             raise Http404
103         tags.append(tag)
104         
105     books = models.Book.objects.with_all(tags)
106     
107     if request.user.is_authenticated():
108         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
109     else:
110         extra_where = 'NOT catalogue_tag.category = "set"'
111     related_tags = models.Tag.objects.related_for_model(tags, models.Book, counts=True, extra={'where': [extra_where]})
112     categories = split_tags(related_tags)
113     
114     form = forms.SearchForm()
115     
116     return render_to_response('catalogue/tagged_book_list.html', dict(
117         tags=tags,
118         form=form,
119         books=books,
120         categories=categories,
121     ), context_instance=RequestContext(request))
122
123
124 def book_detail(request, slug):
125     book = get_object_or_404(models.Book, slug=slug)
126     tags = list(book.tags.filter(~Q(category='set')))
127     categories = split_tags(tags)
128     search_form = forms.SearchForm()
129     
130     return render_to_response('catalogue/book_detail.html', locals(),
131         context_instance=RequestContext(request))
132
133
134 @login_required
135 def book_sets(request, slug):
136     book = get_object_or_404(models.Book, slug=slug)
137     user_sets = models.Tag.objects.filter(category='set', user=request.user)
138     book_sets = book.tags.filter(category='set', user=request.user)
139     
140     if request.method == 'POST':
141         form = forms.BookSetsForm(book, request.user, request.POST)
142         if form.is_valid():
143             book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
144                 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
145             if request.is_ajax():
146                 return HttpResponse('<p>Zestawy zostały zapisane</p>')
147             else:
148                 return HttpResponseRedirect('/')
149     else:
150         form = forms.BookSetsForm(book, request.user)
151         new_set_form = forms.NewSetForm()
152     
153     return render_to_response('catalogue/book_sets.html', locals(),
154         context_instance=RequestContext(request))
155
156
157 @login_required
158 @require_POST
159 def new_set(request):
160     new_set_form = forms.NewSetForm(request.POST)
161     if new_set_form.is_valid():
162         new_set = new_set_form.save(request.user)
163         return HttpResponse('<p>Zestaw <strong>%s</strong> został utworzony</p>' % new_set)
164     
165     return render_to_response('catalogue/book_sets.html', locals(),
166             context_instance=RequestContext(request))
167