Added cache control headers and removed unused fragment_sets view.
[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 from django.views.decorators import cache
16
17 from catalogue import models
18 from catalogue import forms
19 from catalogue.utils import split_tags
20 from newtagging import views as newtagging_views
21
22
23 class LazyEncoder(simplejson.JSONEncoder):
24     def default(self, obj):
25         if isinstance(obj, Promise):
26             return force_unicode(obj)
27         return obj
28
29
30 @cache.cache_control(must_revalidate=True, max_age=3600)
31 def main_page(request):    
32     if request.user.is_authenticated():
33         shelves = models.Tag.objects.filter(category='set', user=request.user)
34         new_set_form = forms.NewSetForm()
35     extra_where = 'NOT catalogue_tag.category = "set"'
36     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
37     fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
38         extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
39     categories = split_tags(tags)
40     
41     form = forms.SearchForm()
42     return render_to_response('catalogue/main_page.html', locals(),
43         context_instance=RequestContext(request))
44
45
46 def book_list(request):
47     books = models.Book.objects.all()
48     form = forms.SearchForm()
49     
50     books_by_first_letter = SortedDict()
51     for book in books:
52         books_by_first_letter.setdefault(book.title[0], []).append(book)
53     
54     return render_to_response('catalogue/book_list.html', locals(),
55         context_instance=RequestContext(request))
56
57
58 @cache.cache_control(must_revalidate=True, max_age=3600)
59 def tagged_object_list(request, tags=''):
60     # Prevent DoS attacks on our database
61     if len(tags.split('/')) > 6:
62         raise Http404
63         
64     try:
65         tags = models.Tag.get_tag_list(tags)
66     except models.Tag.DoesNotExist:
67         raise Http404
68     
69     model = models.Book
70     shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
71     theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
72     if theme_is_set:
73         model = models.Fragment
74
75     extra_where = 'NOT catalogue_tag.category = "set"'
76     related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
77     categories = split_tags(related_tags)
78
79     if not theme_is_set:
80         model=models.Book.objects.filter(parent=None)
81     
82     return newtagging_views.tagged_object_list(
83         request,
84         tag_model=models.Tag,
85         queryset_or_model=model,
86         tags=tags,
87         template_name='catalogue/tagged_object_list.html',
88         extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set },
89     )
90
91
92 def book_detail(request, slug):
93     book = get_object_or_404(models.Book, slug=slug)
94     tags = list(book.tags.filter(~Q(category='set')))
95     categories = split_tags(tags)
96     book_children = book.children.all().order_by('parent_number')
97     
98     form = forms.SearchForm()
99     return render_to_response('catalogue/book_detail.html', locals(),
100         context_instance=RequestContext(request))
101
102
103 def book_text(request, slug):
104     book = get_object_or_404(models.Book, slug=slug)
105     book_themes = {}
106     for fragment in book.fragments.all():
107         for theme in fragment.tags.filter(category='theme'):
108             book_themes.setdefault(theme, []).append(fragment)
109     
110     book_themes = book_themes.items()
111     book_themes.sort(key=lambda s: s[0].sort_key)
112     return render_to_response('catalogue/book_text.html', locals(),
113         context_instance=RequestContext(request))
114
115
116 # ==========
117 # = Search =
118 # ==========
119 def search(request):
120     query = request.GET.get('q', '')
121     tags = request.GET.get('tags', '')
122     if tags == '':
123         tags = []
124
125     try:
126         tag_list = models.Tag.get_tag_list(tags)
127         tag = models.Tag.objects.get(name=query)
128     except models.Tag.DoesNotExist:
129         try:
130             book = models.Book.objects.get(title=query)
131             return HttpResponseRedirect(book.get_absolute_url())
132         except models.Book.DoesNotExist:
133             return HttpResponseRedirect(reverse('catalogue.views.main_page'))
134     else:
135         tag_list.append(tag)
136         return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list', 
137             kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
138         ))
139
140
141 def tags_starting_with(request):
142     try:
143         prefix = request.GET['q']
144         if len(prefix) < 2:
145             raise KeyError
146
147         books = models.Book.objects.filter(title__icontains=prefix)
148         tags = models.Tag.objects.filter(name__icontains=prefix)
149         if request.user.is_authenticated():
150             tags = tags.filter(~Q(category='set') | Q(user=request.user))
151         else:
152             tags = tags.filter(~Q(category='set'))
153
154         completions = [book.title for book in books] + [tag.name for tag in tags]
155
156         return HttpResponse('\n'.join(completions))    
157
158     except KeyError:
159         return HttpResponse('')
160
161
162 # ====================
163 # = Shelf management =
164 # ====================
165 @login_required
166 @cache.cache_control(must_revalidate=True, max_age=3600, private=True)
167 def user_shelves(request):
168     shelves = models.Tag.objects.filter(category='set', user=request.user)
169     new_set_form = forms.NewSetForm()
170     return render_to_response('catalogue/user_shelves.html', locals(),
171             context_instance=RequestContext(request))
172
173
174 @cache.cache_control(must_revalidate=True, max_age=3600, private=True)
175 def book_sets(request, slug):
176     book = get_object_or_404(models.Book, slug=slug)
177     user_sets = models.Tag.objects.filter(category='set', user=request.user)
178     book_sets = book.tags.filter(category='set', user=request.user)
179     
180     if not request.user.is_authenticated():
181         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
182     
183     if request.method == 'POST':
184         form = forms.ObjectSetsForm(book, request.user, request.POST)
185         if form.is_valid():
186             book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
187                 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
188             if request.is_ajax():
189                 return HttpResponse('<p>Półki zostały zapisane.</p>')
190             else:
191                 return HttpResponseRedirect('/')
192     else:
193         form = forms.ObjectSetsForm(book, request.user)
194         new_set_form = forms.NewSetForm()
195     
196     return render_to_response('catalogue/book_sets.html', locals(),
197         context_instance=RequestContext(request))
198
199
200 @login_required
201 @require_POST
202 @cache.never_cache
203 def new_set(request):
204     new_set_form = forms.NewSetForm(request.POST)
205     if new_set_form.is_valid():
206         new_set = new_set_form.save(request.user)
207
208         if request.is_ajax():
209             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
210         else:
211             return HttpResponseRedirect('/')
212
213     return render_to_response('catalogue/book_sets.html', locals(),
214             context_instance=RequestContext(request))
215
216
217 @login_required
218 @require_POST
219 @cache.never_cache
220 def delete_shelf(request, slug):
221     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
222     user_set.delete()
223
224     if request.is_ajax():
225         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
226     else:
227         return HttpResponseRedirect('/')
228
229
230 # ==================
231 # = Authentication =
232 # ==================
233 @require_POST
234 @cache.never_cache
235 def login(request):
236     form = AuthenticationForm(data=request.POST, prefix='login')
237     if form.is_valid():
238         auth.login(request, form.get_user())
239         response_data = {'success': True, 'errors': {}}
240     else:
241         response_data = {'success': False, 'errors': form.errors}
242     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
243
244
245 @require_POST
246 @cache.never_cache
247 def register(request):
248     registration_form = UserCreationForm(request.POST, prefix='registration')
249     if registration_form.is_valid():
250         user = registration_form.save()
251         user = auth.authenticate(
252             username=registration_form.cleaned_data['username'], 
253             password=registration_form.cleaned_data['password1']
254         )
255         auth.login(request, user)
256         response_data = {'success': True, 'errors': {}}
257     else:
258         response_data = {'success': False, 'errors': registration_form.errors}
259     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
260
261
262 @cache.never_cache
263 def logout_then_redirect(request):
264     auth.logout(request)
265     return HttpResponseRedirect(request.GET.get('next', '/'))
266