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