0166133a758a3cbeecbe35668b2b798cd765a5b2
[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 from django.contrib import auth
11 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
12 from django.utils import simplejson
13 from django.utils.functional import Promise
14 from django.utils.encoding import force_unicode
15
16 from newtagging.views import tagged_object_list
17 from catalogue import models
18 from catalogue import forms
19 from catalogue.utils import split_tags
20
21
22 class LazyEncoder(simplejson.JSONEncoder):
23     def default(self, obj):
24         if isinstance(obj, Promise):
25             return force_unicode(obj)
26         return obj
27
28
29 def search(request):
30     query = request.GET.get('q', '')
31     tags = request.GET.get('tags', '')
32     if tags == '':
33         tags = []
34     
35     try:
36         tag_list = models.Tag.get_tag_list(tags)
37         tag = models.Tag.objects.get(name=query)
38     except models.Tag.DoesNotExist:
39         print "%r, %r" % (query, tags)
40         try:
41             book = models.Book.objects.get(title=query)
42         except models.Book.DoesNotExist:
43             return HttpResponseRedirect(reverse('catalogue.views.main_page'))
44     else:
45         tag_list.append(tag)
46         return HttpResponseRedirect(reverse('catalogue.views.tagged_book_list', 
47             kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
48         ))
49
50
51 def tags_starting_with(request):
52     try:
53         prefix = request.GET['q']
54         if len(prefix) < 2:
55             raise KeyError
56             
57         books = models.Book.objects.filter(title__icontains=prefix)
58         tags = models.Tag.objects.filter(name__icontains=prefix)
59         if request.user.is_authenticated():
60             tags = tags.filter(~Q(category='set') | Q(user=request.user))
61         else:
62             tags = tags.filter(~Q(category='set'))
63         
64         completions = [book.title for book in books] + [tag.name for tag in tags]
65
66         return HttpResponse('\n'.join(completions))    
67     
68     except KeyError:
69         return HttpResponse('')
70
71
72 def main_page(request):    
73     if request.user.is_authenticated():
74         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
75     else:
76         extra_where = 'NOT catalogue_tag.category = "set"'
77     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
78     categories = split_tags(tags)
79     
80     form = forms.SearchForm()
81     return render_to_response('catalogue/main_page.html', locals(),
82         context_instance=RequestContext(request))
83
84
85 def book_list(request):
86     books = models.Book.objects.all()
87     form = forms.SearchForm()
88     
89     books_by_first_letter = SortedDict()
90     for book in books:
91         books_by_first_letter.setdefault(book.title[0], []).append(book)
92     
93     return render_to_response('catalogue/book_list.html', locals(),
94         context_instance=RequestContext(request))
95
96
97 def tagged_book_list(request, tags=''):
98     try:
99         tags = models.Tag.get_tag_list(tags)
100     except models.Tag.DoesNotExist:
101         raise Http404
102         
103     if request.user.is_authenticated():
104         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
105     else:
106         extra_where = 'NOT catalogue_tag.category = "set"'
107     related_tags = models.Tag.objects.related_for_model(tags, models.Book, counts=True, extra={'where': [extra_where]})
108     categories = split_tags(related_tags)
109
110     return tagged_object_list(
111         request,
112         tag_model=models.Tag,
113         queryset_or_model=models.Book,
114         tags=tags,
115         template_name='catalogue/tagged_book_list.html',
116         extra_context = {'categories': categories },
117     )
118
119
120 def book_detail(request, slug):
121     book = get_object_or_404(models.Book, slug=slug)
122     tags = list(book.tags.filter(~Q(category='set')))
123     categories = split_tags(tags)
124     
125     return render_to_response('catalogue/book_detail.html', locals(),
126         context_instance=RequestContext(request))
127
128
129 def logout_then_redirect(request):
130     auth.logout(request)
131     return HttpResponseRedirect(request.GET.get('next', '/'))
132
133
134 @require_POST
135 def register(request):
136     registration_form = UserCreationForm(request.POST, prefix='registration')
137     if registration_form.is_valid():
138         user = registration_form.save()
139         user = auth.authenticate(
140             username=registration_form.cleaned_data['username'], 
141             password=registration_form.cleaned_data['password1']
142         )
143         auth.login(request, user)
144         response_data = {'success': True, 'errors': {}}
145     else:
146         response_data = {'success': False, 'errors': registration_form.errors}
147     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
148
149
150 @require_POST
151 def login(request):
152     form = AuthenticationForm(data=request.POST, prefix='login')
153     if form.is_valid():
154         auth.login(request, form.get_user())
155         response_data = {'success': True, 'errors': {}}
156     else:
157         response_data = {'success': False, 'errors': form.errors}
158     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
159
160
161 @login_required
162 def book_sets(request, slug):
163     book = get_object_or_404(models.Book, slug=slug)
164     user_sets = models.Tag.objects.filter(category='set', user=request.user)
165     book_sets = book.tags.filter(category='set', user=request.user)
166     
167     if request.method == 'POST':
168         form = forms.BookSetsForm(book, request.user, request.POST)
169         if form.is_valid():
170             book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
171                 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
172             if request.is_ajax():
173                 return HttpResponse('<p>Zestawy zostały zapisane</p>')
174             else:
175                 return HttpResponseRedirect('/')
176     else:
177         form = forms.BookSetsForm(book, request.user)
178         new_set_form = forms.NewSetForm()
179     
180     return render_to_response('catalogue/book_sets.html', locals(),
181         context_instance=RequestContext(request))
182
183
184 @login_required
185 @require_POST
186 def new_set(request):
187     new_set_form = forms.NewSetForm(request.POST)
188     if new_set_form.is_valid():
189         new_set = new_set_form.save(request.user)
190         return HttpResponse('<p>Zestaw <strong>%s</strong> został utworzony</p>' % new_set)
191     
192     return render_to_response('catalogue/book_sets.html', locals(),
193             context_instance=RequestContext(request))
194