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