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