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