3b9f31d16c6742ab4c8af25809bc847cdb88d9db
[wolnelektury.git] / apps / 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 catalogue import models
17 from catalogue import forms
18 from catalogue.utils import split_tags
19 from newtagging import views as newtagging_views
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         try:
40             book = models.Book.objects.get(title=query)
41             return HttpResponseRedirect(book.get_absolute_url())
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_object_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         shelves = models.Tag.objects.filter(category='set', user=request.user)
75         new_set_form = forms.NewSetForm()
76         extra_where = '((NOT catalogue_tag.category = "set" AND catalogue_tag.main_page = 1) OR catalogue_tag.user_id = %d)' % request.user.id
77     else:
78         extra_where = 'NOT catalogue_tag.category = "set" AND catalogue_tag.main_page = 1'
79     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
80     fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
81         extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
82     categories = split_tags(tags)
83     
84     form = forms.SearchForm()
85     
86     return render_to_response('catalogue/main_page.html', locals(),
87         context_instance=RequestContext(request))
88
89
90 def book_list(request):
91     books = models.Book.objects.all()
92     form = forms.SearchForm()
93     
94     books_by_first_letter = SortedDict()
95     for book in books:
96         books_by_first_letter.setdefault(book.title[0], []).append(book)
97     
98     return render_to_response('catalogue/book_list.html', locals(),
99         context_instance=RequestContext(request))
100
101
102 def tagged_object_list(request, tags=''):
103     try:
104         tags = models.Tag.get_tag_list(tags)
105     except models.Tag.DoesNotExist:
106         raise Http404
107     
108     model = models.Book
109     theme_is_set = any(tag.category == 'theme' for tag in tags)
110     if theme_is_set:
111         model = models.Fragment
112     
113     if request.user.is_authenticated():
114         extra_where = '(NOT catalogue_tag.category = "set" OR catalogue_tag.user_id = %d)' % request.user.id
115     else:
116         extra_where = 'NOT catalogue_tag.category = "set"'
117     related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
118     categories = split_tags(related_tags)
119
120     return newtagging_views.tagged_object_list(
121         request,
122         tag_model=models.Tag,
123         queryset_or_model=model,
124         tags=tags,
125         template_name='catalogue/tagged_object_list.html',
126         extra_context = {'categories': categories },
127     )
128
129
130 def book_detail(request, slug):
131     book = get_object_or_404(models.Book, slug=slug)
132     tags = list(book.tags.filter(~Q(category='set')))
133     categories = split_tags(tags)
134     
135     form = forms.SearchForm()
136     return render_to_response('catalogue/book_detail.html', locals(),
137         context_instance=RequestContext(request))
138
139
140 def logout_then_redirect(request):
141     auth.logout(request)
142     return HttpResponseRedirect(request.GET.get('next', '/'))
143
144
145 @require_POST
146 def register(request):
147     registration_form = UserCreationForm(request.POST, prefix='registration')
148     if registration_form.is_valid():
149         user = registration_form.save()
150         user = auth.authenticate(
151             username=registration_form.cleaned_data['username'], 
152             password=registration_form.cleaned_data['password1']
153         )
154         auth.login(request, user)
155         response_data = {'success': True, 'errors': {}}
156     else:
157         response_data = {'success': False, 'errors': registration_form.errors}
158     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
159
160
161 @require_POST
162 def login(request):
163     form = AuthenticationForm(data=request.POST, prefix='login')
164     if form.is_valid():
165         auth.login(request, form.get_user())
166         response_data = {'success': True, 'errors': {}}
167     else:
168         response_data = {'success': False, 'errors': form.errors}
169     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
170
171
172 def book_sets(request, slug):
173     book = get_object_or_404(models.Book, slug=slug)
174     user_sets = models.Tag.objects.filter(category='set', user=request.user)
175     book_sets = book.tags.filter(category='set', user=request.user)
176     
177     if not request.user.is_authenticated():
178         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
179     
180     if request.method == 'POST':
181         form = forms.ObjectSetsForm(book, request.user, request.POST)
182         if form.is_valid():
183             book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
184                 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
185             if request.is_ajax():
186                 return HttpResponse('<p>Półki zostały zapisane.</p>')
187             else:
188                 return HttpResponseRedirect('/')
189     else:
190         form = forms.ObjectSetsForm(book, request.user)
191         new_set_form = forms.NewSetForm()
192     
193     return render_to_response('catalogue/book_sets.html', locals(),
194         context_instance=RequestContext(request))
195
196
197 def fragment_sets(request, id):
198     fragment = get_object_or_404(models.Fragment, pk=id)
199     user_sets = models.Tag.objects.filter(category='set', user=request.user)
200     fragment_sets = fragment.tags.filter(category='set', user=request.user)
201
202     if not request.user.is_authenticated():
203         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
204
205     if request.method == 'POST':
206         form = forms.ObjectSetsForm(fragment, request.user, request.POST)
207         if form.is_valid():
208             fragment.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
209                 list(fragment.tags.filter(~Q(category='set') | ~Q(user=request.user))))
210             if request.is_ajax():
211                 return HttpResponse('<p>Półki zostały zapisane.</p>')
212             else:
213                 return HttpResponseRedirect('/')
214     else:
215         form = forms.ObjectSetsForm(fragment, request.user)
216         new_set_form = forms.NewSetForm()
217
218     return render_to_response('catalogue/fragment_sets.html', locals(),
219         context_instance=RequestContext(request))
220
221
222 @login_required
223 @require_POST
224 def new_set(request):
225     new_set_form = forms.NewSetForm(request.POST)
226     if new_set_form.is_valid():
227         new_set = new_set_form.save(request.user)
228         
229         if request.is_ajax():
230             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
231         else:
232             return HttpResponseRedirect('/')
233     
234     return render_to_response('catalogue/book_sets.html', locals(),
235             context_instance=RequestContext(request))
236
237
238 @login_required
239 @require_POST
240 def delete_shelf(request, slug):
241     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
242     user_set.delete()
243     
244     if request.is_ajax():
245         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
246     else:
247         return HttpResponseRedirect('/')
248
249
250 @login_required
251 def user_shelves(request):
252     shelves = models.Tag.objects.filter(category='set', user=request.user)
253     new_set_form = forms.NewSetForm()
254     return render_to_response('catalogue/user_shelves.html', locals(),
255             context_instance=RequestContext(request))
256