standarize ajaxable dialogs
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import re
6 import itertools
7 from datetime import datetime
8
9 from django.conf import settings
10 from django.template import RequestContext
11 from django.shortcuts import render_to_response, get_object_or_404
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
13 from django.core.urlresolvers import reverse
14 from django.db.models import Count, Sum, Q
15 from django.contrib.auth.decorators import login_required, user_passes_test
16 from django.utils.datastructures import SortedDict
17 from django.views.decorators.http import require_POST
18 from django.contrib import auth
19 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
20 from django.utils.http import urlquote_plus
21 from django.views.decorators import cache
22 from django.utils import translation
23 from django.utils.translation import ugettext as _
24 from django.views.generic.list_detail import object_list
25
26 from ajaxable.utils import LazyEncoder, JSONResponse
27 from catalogue import models
28 from catalogue import forms
29 from catalogue.utils import split_tags, AttachmentHttpResponse, async_build_pdf
30 from catalogue.tasks import touch_tag
31 from pdcounter import models as pdcounter_models
32 from pdcounter import views as pdcounter_views
33 from suggest.forms import PublishingSuggestForm
34
35 from os import path
36
37 staff_required = user_passes_test(lambda user: user.is_staff)
38
39
40 def catalogue(request):
41     tags = models.Tag.objects.exclude(
42         category__in=('set', 'book')).exclude(book_count=0)
43     tags = list(tags)
44     for tag in tags:
45         tag.count = tag.book_count
46     categories = split_tags(tags)
47     fragment_tags = categories.get('theme', [])
48
49     form = forms.SearchForm()
50     return render_to_response('catalogue/catalogue.html', locals(),
51         context_instance=RequestContext(request))
52
53
54 def book_list(request, filter=None, template_name='catalogue/book_list.html'):
55     """ generates a listing of all books, optionally filtered with a test function """
56
57     form = forms.SearchForm()
58
59     books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
60     books_nav = SortedDict()
61     for tag in books_by_author:
62         if books_by_author[tag]:
63             books_nav.setdefault(tag.sort_key[0], []).append(tag)
64
65     return render_to_response(template_name, locals(),
66         context_instance=RequestContext(request))
67
68
69 def audiobook_list(request):
70     return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
71                      template_name='catalogue/audiobook_list.html')
72
73
74 def daisy_list(request):
75     return book_list(request, Q(media__type='daisy'),
76                      template_name='catalogue/daisy_list.html')
77
78
79 def differentiate_tags(request, tags, ambiguous_slugs):
80     beginning = '/'.join(tag.url_chunk for tag in tags)
81     unparsed = '/'.join(ambiguous_slugs[1:])
82     options = []
83     for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
84         options.append({
85             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
86             'tags': [tag]
87         })
88     return render_to_response('catalogue/differentiate_tags.html',
89                 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
90                 context_instance=RequestContext(request))
91
92
93 def tagged_object_list(request, tags=''):
94     try:
95         tags = models.Tag.get_tag_list(tags)
96     except models.Tag.DoesNotExist:
97         chunks = tags.split('/')
98         if len(chunks) == 2 and chunks[0] == 'autor':
99             return pdcounter_views.author_detail(request, chunks[1])
100         else:
101             raise Http404
102     except models.Tag.MultipleObjectsReturned, e:
103         return differentiate_tags(request, e.tags, e.ambiguous_slugs)
104     except models.Tag.UrlDeprecationWarning, e:
105         return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
106
107     try:
108         if len(tags) > settings.MAX_TAG_LIST:
109             raise Http404
110     except AttributeError:
111         pass
112
113     if len([tag for tag in tags if tag.category == 'book']):
114         raise Http404
115
116     theme_is_set = [tag for tag in tags if tag.category == 'theme']
117     shelf_is_set = [tag for tag in tags if tag.category == 'set']
118     only_shelf = shelf_is_set and len(tags) == 1
119     only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
120
121     objects = only_author = None
122     categories = {}
123
124     if theme_is_set:
125         shelf_tags = [tag for tag in tags if tag.category == 'set']
126         fragment_tags = [tag for tag in tags if tag.category != 'set']
127         fragments = models.Fragment.tagged.with_all(fragment_tags)
128
129         if shelf_tags:
130             books = models.Book.tagged.with_all(shelf_tags).order_by()
131             l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
132             fragments = models.Fragment.tagged.with_any(l_tags, fragments)
133
134         # newtagging goes crazy if we just try:
135         #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
136         #                    extra={'where': ["catalogue_tag.category != 'book'"]})
137         fragment_keys = [fragment.pk for fragment in fragments]
138         if fragment_keys:
139             related_tags = models.Fragment.tags.usage(counts=True,
140                                 filters={'pk__in': fragment_keys},
141                                 extra={'where': ["catalogue_tag.category != 'book'"]})
142             related_tags = (tag for tag in related_tags if tag not in fragment_tags)
143             categories = split_tags(related_tags)
144
145             objects = fragments
146     else:
147         if shelf_is_set:
148             objects = models.Book.tagged.with_all(tags)
149         else:
150             objects = models.Book.tagged_top_level(tags)
151
152         # get related tags from `tag_counter` and `theme_counter`
153         related_counts = {}
154         tags_pks = [tag.pk for tag in tags]
155         for book in objects:
156             for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
157                 if tag_pk in tags_pks:
158                     continue
159                 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
160         related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
161         related_tags = [tag for tag in related_tags if tag not in tags]
162         for tag in related_tags:
163             tag.count = related_counts[tag.pk]
164
165         categories = split_tags(related_tags)
166         del related_tags
167
168     if not objects:
169         only_author = len(tags) == 1 and tags[0].category == 'author'
170         objects = models.Book.objects.none()
171
172     return object_list(
173         request,
174         objects,
175         template_name='catalogue/tagged_object_list.html',
176         extra_context={
177             'categories': categories,
178             'only_shelf': only_shelf,
179             'only_author': only_author,
180             'only_my_shelf': only_my_shelf,
181             'formats_form': forms.DownloadFormatsForm(),
182             'tags': tags,
183         }
184     )
185
186
187 def book_fragments(request, book, theme_slug):
188     kwargs = models.Book.split_urlid(book)
189     if kwargs is None:
190         raise Http404
191     book = get_object_or_404(models.Book, **kwargs)
192
193     book_tag = book.book_tag()
194     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
195     fragments = models.Fragment.tagged.with_all([book_tag, theme])
196
197     form = forms.SearchForm()
198     return render_to_response('catalogue/book_fragments.html', locals(),
199         context_instance=RequestContext(request))
200
201
202 def book_detail(request, book):
203     kwargs = models.Book.split_urlid(book)
204     if kwargs is None:
205         raise Http404
206     try:
207         book = models.Book.objects.get(**kwargs)
208     except models.Book.DoesNotExist:
209         return pdcounter_views.book_stub_detail(request, kwargs['slug'])
210     
211     book_tag = book.book_tag()
212     tags = list(book.tags.filter(~Q(category='set')))
213     categories = split_tags(tags)
214     book_children = book.children.all().order_by('parent_number', 'sort_key')
215     
216     _book = book
217     parents = []
218     while _book.parent:
219         parents.append(_book.parent)
220         _book = _book.parent
221     parents = reversed(parents)
222
223     theme_counter = book.theme_counter
224     book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
225     for tag in book_themes:
226         tag.count = theme_counter[tag.pk]
227
228     extra_info = book.get_extra_info_value()
229     hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
230
231     projects = set()
232     for m in book.media.filter(type='mp3'):
233         # ogg files are always from the same project
234         meta = m.get_extra_info_value()
235         project = meta.get('project')
236         if not project:
237             # temporary fallback
238             project = u'CzytamySłuchając'
239
240         projects.add((project, meta.get('funded_by', '')))
241     projects = sorted(projects)
242
243     form = forms.SearchForm()
244     custom_pdf_form = forms.CustomPDFForm()
245     return render_to_response('catalogue/book_detail.html', locals(),
246         context_instance=RequestContext(request))
247
248
249 def book_text(request, book):
250     kwargs = models.Book.split_fileid(book)
251     if kwargs is None:
252         raise Http404
253     book = get_object_or_404(models.Book, **kwargs)
254
255     if not book.has_html_file():
256         raise Http404
257     book_themes = {}
258     for fragment in book.fragments.all():
259         for theme in fragment.tags.filter(category='theme'):
260             book_themes.setdefault(theme, []).append(fragment)
261
262     book_themes = book_themes.items()
263     book_themes.sort(key=lambda s: s[0].sort_key)
264     return render_to_response('catalogue/book_text.html', locals(),
265         context_instance=RequestContext(request))
266
267
268 # ==========
269 # = Search =
270 # ==========
271
272 def _no_diacritics_regexp(query):
273     """ returns a regexp for searching for a query without diacritics
274
275     should be locale-aware """
276     names = {
277         u'a':u'aąĄ', u'c':u'cćĆ', u'e':u'eęĘ', u'l': u'lłŁ', u'n':u'nńŃ', u'o':u'oóÓ', u's':u'sśŚ', u'z':u'zźżŹŻ',
278         u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
279         }
280     def repl(m):
281         l = m.group()
282         return u"(%s)" % '|'.join(names[l])
283     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
284
285 def unicode_re_escape(query):
286     """ Unicode-friendly version of re.escape """
287     return re.sub('(?u)(\W)', r'\\\1', query)
288
289 def _word_starts_with(name, prefix):
290     """returns a Q object getting models having `name` contain a word
291     starting with `prefix`
292
293     We define word characters as alphanumeric and underscore, like in JS.
294
295     Works for MySQL, PostgreSQL, Oracle.
296     For SQLite, _sqlite* version is substituted for this.
297     """
298     kwargs = {}
299
300     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
301     # can't use [[:<:]] (word start),
302     # but we want both `xy` and `(xy` to catch `(xyz)`
303     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
304
305     return Q(**kwargs)
306
307
308 def _word_starts_with_regexp(prefix):
309     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
310     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
311
312
313 def _sqlite_word_starts_with(name, prefix):
314     """ version of _word_starts_with for SQLite
315
316     SQLite in Django uses Python re module
317     """
318     kwargs = {}
319     kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
320     return Q(**kwargs)
321
322
323 if hasattr(settings, 'DATABASES'):
324     if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
325         _word_starts_with = _sqlite_word_starts_with
326 elif settings.DATABASE_ENGINE == 'sqlite3':
327     _word_starts_with = _sqlite_word_starts_with
328
329
330 class App():
331     def __init__(self, name, view):
332         self.name = name
333         self._view = view
334         self.lower = name.lower()
335         self.category = 'application'
336     def view(self):
337         return reverse(*self._view)
338
339 _apps = (
340     App(u'Leśmianator', (u'lesmianator', )),
341     )
342
343
344 def _tags_starting_with(prefix, user=None):
345     prefix = prefix.lower()
346     # PD counter
347     book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
348     authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
349
350     books = models.Book.objects.filter(_word_starts_with('title', prefix))
351     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
352     if user and user.is_authenticated():
353         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
354     else:
355         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
356
357     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
358     return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
359
360
361 def _get_result_link(match, tag_list):
362     if isinstance(match, models.Tag):
363         return reverse('catalogue.views.tagged_object_list',
364             kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
365         )
366     elif isinstance(match, App):
367         return match.view()
368     else:
369         return match.get_absolute_url()
370
371
372 def _get_result_type(match):
373     if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
374         type = 'book'
375     else:
376         type = match.category
377     return type
378
379
380 def books_starting_with(prefix):
381     prefix = prefix.lower()
382     return models.Book.objects.filter(_word_starts_with('title', prefix))
383
384
385 def find_best_matches(query, user=None):
386     """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
387
388     Returns a with:
389       - zero elements when nothing is found,
390       - one element when a best result is found,
391       - more then one element on multiple exact matches
392
393     Raises a ValueError on too short a query.
394     """
395
396     query = query.lower()
397     if len(query) < 2:
398         raise ValueError("query must have at least two characters")
399
400     result = tuple(_tags_starting_with(query, user))
401     # remove pdcounter stuff
402     book_titles = set(match.pretty_title().lower() for match in result
403                       if isinstance(match, models.Book))
404     authors = set(match.name.lower() for match in result
405                   if isinstance(match, models.Tag) and match.category=='author')
406     result = tuple(res for res in result if not (
407                  (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
408                  or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
409              ))
410
411     exact_matches = tuple(res for res in result if res.name.lower() == query)
412     if exact_matches:
413         return exact_matches
414     else:
415         return tuple(result)[:1]
416
417
418 def search(request):
419     tags = request.GET.get('tags', '')
420     prefix = request.GET.get('q', '')
421
422     try:
423         tag_list = models.Tag.get_tag_list(tags)
424     except:
425         tag_list = []
426
427     try:
428         result = find_best_matches(prefix, request.user)
429     except ValueError:
430         return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
431             context_instance=RequestContext(request))
432
433     if len(result) == 1:
434         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
435     elif len(result) > 1:
436         return render_to_response('catalogue/search_multiple_hits.html',
437             {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
438             context_instance=RequestContext(request))
439     else:
440         form = PublishingSuggestForm(initial={"books": prefix + ", "})
441         return render_to_response('catalogue/search_no_hits.html', 
442             {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
443             context_instance=RequestContext(request))
444
445
446 def tags_starting_with(request):
447     prefix = request.GET.get('q', '')
448     # Prefix must have at least 2 characters
449     if len(prefix) < 2:
450         return HttpResponse('')
451     tags_list = []
452     result = ""   
453     for tag in _tags_starting_with(prefix, request.user):
454         if not tag.name in tags_list:
455             result += "\n" + tag.name
456             tags_list.append(tag.name)
457     return HttpResponse(result)
458
459 def json_tags_starting_with(request, callback=None):
460     # Callback for JSONP
461     prefix = request.GET.get('q', '')
462     callback = request.GET.get('callback', '')
463     # Prefix must have at least 2 characters
464     if len(prefix) < 2:
465         return HttpResponse('')
466     tags_list = []
467     for tag in _tags_starting_with(prefix, request.user):
468         if not tag.name in tags_list:
469             tags_list.append(tag.name)
470     if request.GET.get('mozhint', ''):
471         result = [prefix, tags_list]
472     else:
473         result = {"matches": tags_list}
474     return JSONResponse(result, callback)
475
476 # ====================
477 # = Shelf management =
478 # ====================
479 @login_required
480 @cache.never_cache
481 def user_shelves(request):
482     shelves = models.Tag.objects.filter(category='set', user=request.user)
483     new_set_form = forms.NewSetForm()
484     return render_to_response('catalogue/user_shelves.html', locals(),
485             context_instance=RequestContext(request))
486
487 @cache.never_cache
488 def book_sets(request, book):
489     if not request.user.is_authenticated():
490         return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
491
492     kwargs = models.Book.split_urlid(book)
493     if kwargs is None:
494         raise Http404
495     book = get_object_or_404(models.Book, **kwargs)
496
497     user_sets = models.Tag.objects.filter(category='set', user=request.user)
498     book_sets = book.tags.filter(category='set', user=request.user)
499
500     if request.method == 'POST':
501         form = forms.ObjectSetsForm(book, request.user, request.POST)
502         if form.is_valid():
503             old_shelves = list(book.tags.filter(category='set'))
504             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
505
506             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
507                 touch_tag(shelf)
508
509             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
510                 touch_tag(shelf)
511
512             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
513             if request.is_ajax():
514                 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
515             else:
516                 return HttpResponseRedirect('/')
517     else:
518         form = forms.ObjectSetsForm(book, request.user)
519         new_set_form = forms.NewSetForm()
520
521     return render_to_response('catalogue/book_sets.html', locals(),
522         context_instance=RequestContext(request))
523
524
525 @login_required
526 @require_POST
527 @cache.never_cache
528 def remove_from_shelf(request, shelf, book):
529     kwargs = models.Book.split_urlid(book)
530     if kwargs is None:
531         raise Http404
532     book = get_object_or_404(models.Book, **kwargs)
533
534     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
535
536     if shelf in book.tags:
537         models.Tag.objects.remove_tag(book, shelf)
538         touch_tag(shelf)
539
540         return HttpResponse(_('Book was successfully removed from the shelf'))
541     else:
542         return HttpResponse(_('This book is not on the shelf'))
543
544
545 def collect_books(books):
546     """
547     Returns all real books in collection.
548     """
549     result = []
550     for book in books:
551         if len(book.children.all()) == 0:
552             result.append(book)
553         else:
554             result += collect_books(book.children.all())
555     return result
556
557
558 @cache.never_cache
559 def download_shelf(request, slug):
560     """"
561     Create a ZIP archive on disk and transmit it in chunks of 8KB,
562     without loading the whole file into memory. A similar approach can
563     be used for large dynamic PDF files.
564     """
565     from slughifi import slughifi
566     import tempfile
567     import zipfile
568
569     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
570
571     formats = []
572     form = forms.DownloadFormatsForm(request.GET)
573     if form.is_valid():
574         formats = form.cleaned_data['formats']
575     if len(formats) == 0:
576         formats = models.Book.ebook_formats
577
578     # Create a ZIP archive
579     temp = tempfile.TemporaryFile()
580     archive = zipfile.ZipFile(temp, 'w')
581
582     for book in collect_books(models.Book.tagged.with_all(shelf)):
583         fileid = book.fileid()
584         for ebook_format in models.Book.ebook_formats:
585             if ebook_format in formats and book.has_media(ebook_format):
586                 filename = book.get_media(ebook_format).path
587                 archive.write(filename, str('%s.%s' % (fileid, ebook_format)))
588     archive.close()
589
590     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
591     response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
592     response['Content-Length'] = temp.tell()
593
594     temp.seek(0)
595     response.write(temp.read())
596     return response
597
598
599 @cache.never_cache
600 def shelf_book_formats(request, shelf):
601     """"
602     Returns a list of formats of books in shelf.
603     """
604     shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
605
606     formats = {}
607     for ebook_format in models.Book.ebook_formats:
608         formats[ebook_format] = False
609
610     for book in collect_books(models.Book.tagged.with_all(shelf)):
611         for ebook_format in models.Book.ebook_formats:
612             if book.has_media(ebook_format):
613                 formats[ebook_format] = True
614
615     return HttpResponse(LazyEncoder().encode(formats))
616
617
618 @login_required
619 @require_POST
620 @cache.never_cache
621 def new_set(request):
622     new_set_form = forms.NewSetForm(request.POST)
623     if new_set_form.is_valid():
624         new_set = new_set_form.save(request.user)
625
626         if request.is_ajax():
627             return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
628         else:
629             return HttpResponseRedirect('/')
630
631     return HttpResponseRedirect('/')
632
633
634 @login_required
635 @require_POST
636 @cache.never_cache
637 def delete_shelf(request, slug):
638     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
639     user_set.delete()
640
641     if request.is_ajax():
642         return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
643     else:
644         return HttpResponseRedirect('/')
645
646
647 # =========
648 # = Admin =
649 # =========
650 @login_required
651 @staff_required
652 def import_book(request):
653     """docstring for import_book"""
654     book_import_form = forms.BookImportForm(request.POST, request.FILES)
655     if book_import_form.is_valid():
656         try:
657             book_import_form.save()
658         except:
659             import sys
660             import pprint
661             import traceback
662             info = sys.exc_info()
663             exception = pprint.pformat(info[1])
664             tb = '\n'.join(traceback.format_tb(info[2]))
665             return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
666         return HttpResponse(_("Book imported successfully"))
667     else:
668         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
669
670
671 # info views for API
672
673 def book_info(request, id, lang='pl'):
674     book = get_object_or_404(models.Book, id=id)
675     # set language by hand
676     translation.activate(lang)
677     return render_to_response('catalogue/book_info.html', locals(),
678         context_instance=RequestContext(request))
679
680
681 def tag_info(request, id):
682     tag = get_object_or_404(models.Tag, id=id)
683     return HttpResponse(tag.description)
684
685
686 def download_zip(request, format, book=None):
687     kwargs = models.Book.split_fileid(book)
688
689     url = None
690     if format in models.Book.ebook_formats:
691         url = models.Book.zip_format(format)
692     elif format == 'audiobook' and kwargs is not None:
693         book = get_object_or_404(models.Book, **kwargs)
694         url = book.zip_audiobooks()
695     else:
696         raise Http404('No format specified for zip package')
697     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
698
699
700 def download_custom_pdf(request, book_fileid):
701     kwargs = models.Book.split_fileid(book_fileid)
702     if kwargs is None:
703         raise Http404
704     book = get_object_or_404(models.Book, **kwargs)
705
706     if request.method == 'GET':
707         form = forms.CustomPDFForm(request.GET)
708         if form.is_valid():
709             cust = form.customizations
710             pdf_file = models.get_customized_pdf_path(book, cust)
711                 
712             if not path.exists(pdf_file):
713                 result = async_build_pdf.delay(book.id, cust, pdf_file)
714                 result.wait()
715             return AttachmentHttpResponse(file_name=("%s.pdf" % book_fileid), file_path=pdf_file, mimetype="application/pdf")
716         else:
717             raise Http404(_('Incorrect customization options for PDF'))
718     else:
719         raise Http404(_('Bad method'))