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