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