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