de75803a4a28dc0eb0b31b3f2bd98451ff2a0e71
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 import tempfile
3 import zipfile
4
5 from django.template import RequestContext
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponse, HttpResponseRedirect, Http404
8 from django.core.urlresolvers import reverse
9 from django.db.models import Q
10 from django.contrib.auth.decorators import login_required
11 from django.utils.datastructures import SortedDict
12 from django.views.decorators.http import require_POST
13 from django.contrib import auth
14 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
15 from django.utils import simplejson
16 from django.utils.functional import Promise
17 from django.utils.encoding import force_unicode
18 from django.views.decorators import cache
19 from django.core.servers.basehttp import FileWrapper
20
21 from catalogue import models
22 from catalogue import forms
23 from catalogue.utils import split_tags
24 from newtagging import views as newtagging_views
25
26
27 class LazyEncoder(simplejson.JSONEncoder):
28     def default(self, obj):
29         if isinstance(obj, Promise):
30             return force_unicode(obj)
31         return obj
32
33
34 @cache.cache_control(must_revalidate=True, max_age=3600)
35 def main_page(request):    
36     if request.user.is_authenticated():
37         shelves = models.Tag.objects.filter(category='set', user=request.user)
38         new_set_form = forms.NewSetForm()
39     extra_where = 'NOT catalogue_tag.category = "set"'
40     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
41     fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
42         extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
43     categories = split_tags(tags)
44     
45     form = forms.SearchForm()
46     return render_to_response('catalogue/main_page.html', locals(),
47         context_instance=RequestContext(request))
48
49
50 def book_list(request):
51     books = models.Book.objects.all()
52     form = forms.SearchForm()
53     
54     books_by_first_letter = SortedDict()
55     for book in books:
56         books_by_first_letter.setdefault(book.title[0], []).append(book)
57     
58     return render_to_response('catalogue/book_list.html', locals(),
59         context_instance=RequestContext(request))
60
61
62 @cache.cache_control(must_revalidate=True, max_age=3600)
63 def tagged_object_list(request, tags=''):
64     # Prevent DoS attacks on our database
65     if len(tags.split('/')) > 6:
66         raise Http404
67         
68     try:
69         tags = models.Tag.get_tag_list(tags)
70     except models.Tag.DoesNotExist:
71         raise Http404
72     
73     model = models.Book
74     shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
75     theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
76     if theme_is_set:
77         model = models.Fragment
78
79     extra_where = 'NOT catalogue_tag.category = "set"'
80     related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
81     categories = split_tags(related_tags)
82
83     if not theme_is_set:
84         model=models.Book.objects.filter(parent=None)
85     
86     return newtagging_views.tagged_object_list(
87         request,
88         tag_model=models.Tag,
89         queryset_or_model=model,
90         tags=tags,
91         template_name='catalogue/tagged_object_list.html',
92         extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set },
93     )
94
95
96 def book_detail(request, slug):
97     book = get_object_or_404(models.Book, slug=slug)
98     tags = list(book.tags.filter(~Q(category='set')))
99     categories = split_tags(tags)
100     book_children = book.children.all().order_by('parent_number')
101     
102     form = forms.SearchForm()
103     return render_to_response('catalogue/book_detail.html', locals(),
104         context_instance=RequestContext(request))
105
106
107 def book_text(request, slug):
108     book = get_object_or_404(models.Book, slug=slug)
109     book_themes = {}
110     for fragment in book.fragments.all():
111         for theme in fragment.tags.filter(category='theme'):
112             book_themes.setdefault(theme, []).append(fragment)
113     
114     book_themes = book_themes.items()
115     book_themes.sort(key=lambda s: s[0].sort_key)
116     return render_to_response('catalogue/book_text.html', locals(),
117         context_instance=RequestContext(request))
118
119
120 # ==========
121 # = Search =
122 # ==========
123 def search(request):
124     query = request.GET.get('q', '')
125     tags = request.GET.get('tags', '')
126     if tags == '':
127         tags = []
128
129     try:
130         tag_list = models.Tag.get_tag_list(tags)
131         tag = models.Tag.objects.get(name=query)
132     except models.Tag.DoesNotExist:
133         try:
134             book = models.Book.objects.get(title=query)
135             return HttpResponseRedirect(book.get_absolute_url())
136         except models.Book.DoesNotExist:
137             return HttpResponseRedirect(reverse('catalogue.views.main_page'))
138     else:
139         tag_list.append(tag)
140         return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list', 
141             kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
142         ))
143
144
145 def tags_starting_with(request):
146     try:
147         prefix = request.GET['q']
148         if len(prefix) < 2:
149             raise KeyError
150
151         books = models.Book.objects.filter(title__icontains=prefix)
152         tags = models.Tag.objects.filter(name__icontains=prefix)
153         if request.user.is_authenticated():
154             tags = tags.filter(~Q(category='set') | Q(user=request.user))
155         else:
156             tags = tags.filter(~Q(category='set'))
157
158         completions = [book.title for book in books] + [tag.name for tag in tags]
159
160         return HttpResponse('\n'.join(completions))    
161
162     except KeyError:
163         return HttpResponse('')
164
165
166 # ====================
167 # = Shelf management =
168 # ====================
169 @login_required
170 @cache.never_cache
171 def user_shelves(request):
172     shelves = models.Tag.objects.filter(category='set', user=request.user)
173     new_set_form = forms.NewSetForm()
174     return render_to_response('catalogue/user_shelves.html', locals(),
175             context_instance=RequestContext(request))
176
177
178 @cache.never_cache
179 def book_sets(request, slug):
180     book = get_object_or_404(models.Book, slug=slug)
181     user_sets = models.Tag.objects.filter(category='set', user=request.user)
182     book_sets = book.tags.filter(category='set', user=request.user)
183     
184     if not request.user.is_authenticated():
185         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
186     
187     if request.method == 'POST':
188         form = forms.ObjectSetsForm(book, request.user, request.POST)
189         if form.is_valid():
190             book.tags = ([models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']] +
191                 list(book.tags.filter(~Q(category='set') | ~Q(user=request.user))))
192             if request.is_ajax():
193                 return HttpResponse('<p>Półki zostały zapisane.</p>')
194             else:
195                 return HttpResponseRedirect('/')
196     else:
197         form = forms.ObjectSetsForm(book, request.user)
198         new_set_form = forms.NewSetForm()
199     
200     return render_to_response('catalogue/book_sets.html', locals(),
201         context_instance=RequestContext(request))
202
203
204 @cache.cache_control(must_revalidate=True, max_age=1800)
205 def download_shelf(request, slug):
206     """"
207     Create a ZIP archive on disk and transmit it in chunks of 8KB,
208     without loading the whole file into memory. A similar approach can
209     be used for large dynamic PDF files.                                        
210     """
211     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
212     
213     # Create a ZIP archive
214     temp = tempfile.TemporaryFile()
215     archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
216     for book in models.Book.tagged.with_all(shelf):
217         filename = book.html_file.path
218         archive.write(filename, str('%s.html' % book.slug))
219     archive.close()
220     
221     wrapper = FileWrapper(temp)
222     response = HttpResponse(wrapper, content_type='application/zip')
223     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.slug
224     response['Content-Length'] = temp.tell()
225     temp.seek(0)
226     return response
227
228
229 @login_required
230 @require_POST
231 @cache.never_cache
232 def new_set(request):
233     new_set_form = forms.NewSetForm(request.POST)
234     if new_set_form.is_valid():
235         new_set = new_set_form.save(request.user)
236
237         if request.is_ajax():
238             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
239         else:
240             return HttpResponseRedirect('/')
241
242     return render_to_response('catalogue/book_sets.html', locals(),
243             context_instance=RequestContext(request))
244
245
246 @login_required
247 @require_POST
248 @cache.never_cache
249 def delete_shelf(request, slug):
250     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
251     user_set.delete()
252
253     if request.is_ajax():
254         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
255     else:
256         return HttpResponseRedirect('/')
257
258
259 # ==================
260 # = Authentication =
261 # ==================
262 @require_POST
263 @cache.never_cache
264 def login(request):
265     form = AuthenticationForm(data=request.POST, prefix='login')
266     if form.is_valid():
267         auth.login(request, form.get_user())
268         response_data = {'success': True, 'errors': {}}
269     else:
270         response_data = {'success': False, 'errors': form.errors}
271     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
272
273
274 @require_POST
275 @cache.never_cache
276 def register(request):
277     registration_form = UserCreationForm(request.POST, prefix='registration')
278     if registration_form.is_valid():
279         user = registration_form.save()
280         user = auth.authenticate(
281             username=registration_form.cleaned_data['username'], 
282             password=registration_form.cleaned_data['password1']
283         )
284         auth.login(request, user)
285         response_data = {'success': True, 'errors': {}}
286     else:
287         response_data = {'success': False, 'errors': registration_form.errors}
288     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
289
290
291 @cache.never_cache
292 def logout_then_redirect(request):
293     auth.logout(request)
294     return HttpResponseRedirect(request.GET.get('next', '/'))
295