58ef8928f744a7e5963c3c03005e55c9ced42397
[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.never_cache
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')
216     for book in models.Book.tagged.with_all(shelf):
217         if book.pdf_file:
218             filename = book.pdf_file.path
219             print filename
220             archive.write(filename, str('%s.pdf' % book.slug[:7]))
221         if book.odt_file:
222             filename = book.odt_file.path
223             print filename
224             archive.write(filename, str('%s.odt' % book.slug[:7]))
225         if book.txt_file:
226             filename = book.txt_file.path
227             print filename
228             archive.write(filename, str('%s.txt' % book.slug[:7]))
229     archive.close()
230
231     zf = zipfile.ZipFile(temp, 'r')
232     print zf.testzip()
233     print zf.namelist()
234     
235     wrapper = FileWrapper(temp)
236     response = HttpResponse(wrapper, content_type='application/zip')
237     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
238     response['Content-Length'] = temp.tell()
239     print temp.tell()
240     temp.seek(0)
241     return response
242
243
244 @login_required
245 @require_POST
246 @cache.never_cache
247 def new_set(request):
248     new_set_form = forms.NewSetForm(request.POST)
249     if new_set_form.is_valid():
250         new_set = new_set_form.save(request.user)
251
252         if request.is_ajax():
253             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
254         else:
255             return HttpResponseRedirect('/')
256
257     return render_to_response('catalogue/book_sets.html', locals(),
258             context_instance=RequestContext(request))
259
260
261 @login_required
262 @require_POST
263 @cache.never_cache
264 def delete_shelf(request, slug):
265     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
266     user_set.delete()
267
268     if request.is_ajax():
269         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
270     else:
271         return HttpResponseRedirect('/')
272
273
274 # ==================
275 # = Authentication =
276 # ==================
277 @require_POST
278 @cache.never_cache
279 def login(request):
280     form = AuthenticationForm(data=request.POST, prefix='login')
281     if form.is_valid():
282         auth.login(request, form.get_user())
283         response_data = {'success': True, 'errors': {}}
284     else:
285         response_data = {'success': False, 'errors': form.errors}
286     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
287
288
289 @require_POST
290 @cache.never_cache
291 def register(request):
292     registration_form = UserCreationForm(request.POST, prefix='registration')
293     if registration_form.is_valid():
294         user = registration_form.save()
295         user = auth.authenticate(
296             username=registration_form.cleaned_data['username'], 
297             password=registration_form.cleaned_data['password1']
298         )
299         auth.login(request, user)
300         response_data = {'success': True, 'errors': {}}
301     else:
302         response_data = {'success': False, 'errors': registration_form.errors}
303     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
304
305
306 @cache.never_cache
307 def logout_then_redirect(request):
308     auth.logout(request)
309     return HttpResponseRedirect(request.GET.get('next', '/'))
310