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