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.
7 from datetime import datetime
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 import simplejson
21 from django.utils.functional import Promise
22 from django.utils.encoding import force_unicode
23 from django.utils.http import urlquote_plus
24 from django.views.decorators import cache
25 from django.utils import translation
26 from django.utils.translation import ugettext as _
27 from django.views.generic.list_detail import object_list
29 from catalogue import models
30 from catalogue import forms
31 from catalogue.utils import split_tags, AttachmentHttpResponse, async_build_pdf
32 from pdcounter import models as pdcounter_models
33 from pdcounter import views as pdcounter_views
34 from suggest.forms import PublishingSuggestForm
38 staff_required = user_passes_test(lambda user: user.is_staff)
41 class LazyEncoder(simplejson.JSONEncoder):
42 def default(self, obj):
43 if isinstance(obj, Promise):
44 return force_unicode(obj)
47 # shortcut for JSON reponses
48 class JSONResponse(HttpResponse):
49 def __init__(self, data={}, callback=None, **kwargs):
51 kwargs.pop('mimetype', None)
52 data = simplejson.dumps(data)
54 data = callback + "(" + data + ");"
55 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
58 def main_page(request):
59 if request.user.is_authenticated():
60 shelves = models.Tag.objects.filter(category='set', user=request.user)
61 new_set_form = forms.NewSetForm()
63 tags = models.Tag.objects.exclude(category__in=('set', 'book'))
65 tag.count = tag.get_count()
66 categories = split_tags(tags)
67 fragment_tags = categories.get('theme', [])
69 form = forms.SearchForm()
70 return render_to_response('catalogue/main_page.html', locals(),
71 context_instance=RequestContext(request))
74 def book_list(request, filter=None, template_name='catalogue/book_list.html'):
75 """ generates a listing of all books, optionally filtered with a test function """
77 form = forms.SearchForm()
79 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
80 books_nav = SortedDict()
81 for tag in books_by_author:
82 if books_by_author[tag]:
83 books_nav.setdefault(tag.sort_key[0], []).append(tag)
85 return render_to_response(template_name, locals(),
86 context_instance=RequestContext(request))
89 def audiobook_list(request):
90 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
91 template_name='catalogue/audiobook_list.html')
94 def daisy_list(request):
95 return book_list(request, Q(media__type='daisy'),
96 template_name='catalogue/daisy_list.html')
99 def differentiate_tags(request, tags, ambiguous_slugs):
100 beginning = '/'.join(tag.url_chunk for tag in tags)
101 unparsed = '/'.join(ambiguous_slugs[1:])
103 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
105 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
108 return render_to_response('catalogue/differentiate_tags.html',
109 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
110 context_instance=RequestContext(request))
113 def tagged_object_list(request, tags=''):
115 tags = models.Tag.get_tag_list(tags)
116 except models.Tag.DoesNotExist:
117 chunks = tags.split('/')
118 if len(chunks) == 2 and chunks[0] == 'autor':
119 return pdcounter_views.author_detail(request, chunks[1])
122 except models.Tag.MultipleObjectsReturned, e:
123 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
124 except models.Tag.UrlDeprecationWarning, e:
125 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
128 if len(tags) > settings.MAX_TAG_LIST:
130 except AttributeError:
133 if len([tag for tag in tags if tag.category == 'book']):
136 theme_is_set = [tag for tag in tags if tag.category == 'theme']
137 shelf_is_set = [tag for tag in tags if tag.category == 'set']
138 only_shelf = shelf_is_set and len(tags) == 1
139 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
141 objects = only_author = None
145 shelf_tags = [tag for tag in tags if tag.category == 'set']
146 fragment_tags = [tag for tag in tags if tag.category != 'set']
147 fragments = models.Fragment.tagged.with_all(fragment_tags)
150 books = models.Book.tagged.with_all(shelf_tags).order_by()
151 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
152 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
154 # newtagging goes crazy if we just try:
155 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
156 # extra={'where': ["catalogue_tag.category != 'book'"]})
157 fragment_keys = [fragment.pk for fragment in fragments]
159 related_tags = models.Fragment.tags.usage(counts=True,
160 filters={'pk__in': fragment_keys},
161 extra={'where': ["catalogue_tag.category != 'book'"]})
162 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
163 categories = split_tags(related_tags)
168 objects = models.Book.tagged.with_all(tags)
170 objects = models.Book.tagged_top_level(tags)
172 # get related tags from `tag_counter` and `theme_counter`
174 tags_pks = [tag.pk for tag in tags]
176 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
177 if tag_pk in tags_pks:
179 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
180 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
181 related_tags = [tag for tag in related_tags if tag not in tags]
182 for tag in related_tags:
183 tag.count = related_counts[tag.pk]
185 categories = split_tags(related_tags)
189 only_author = len(tags) == 1 and tags[0].category == 'author'
190 objects = models.Book.objects.none()
195 template_name='catalogue/tagged_object_list.html',
197 'categories': categories,
198 'only_shelf': only_shelf,
199 'only_author': only_author,
200 'only_my_shelf': only_my_shelf,
201 'formats_form': forms.DownloadFormatsForm(),
207 def book_fragments(request, book, theme_slug):
208 kwargs = models.Book.split_urlid(book)
211 book = get_object_or_404(models.Book, **kwargs)
213 book_tag = book.book_tag()
214 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
215 fragments = models.Fragment.tagged.with_all([book_tag, theme])
217 form = forms.SearchForm()
218 return render_to_response('catalogue/book_fragments.html', locals(),
219 context_instance=RequestContext(request))
222 def book_detail(request, book):
223 kwargs = models.Book.split_urlid(book)
227 book = models.Book.objects.get(**kwargs)
228 except models.Book.DoesNotExist:
229 return pdcounter_views.book_stub_detail(request, kwargs['slug'])
231 book_tag = book.book_tag()
232 tags = list(book.tags.filter(~Q(category='set')))
233 categories = split_tags(tags)
234 book_children = book.children.all().order_by('parent_number', 'sort_key')
239 parents.append(_book.parent)
241 parents = reversed(parents)
243 theme_counter = book.theme_counter
244 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
245 for tag in book_themes:
246 tag.count = theme_counter[tag.pk]
248 extra_info = book.get_extra_info_value()
249 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
252 for m in book.media.filter(type='mp3'):
253 # ogg files are always from the same project
254 meta = m.get_extra_info_value()
255 project = meta.get('project')
258 project = u'CzytamySłuchając'
260 projects.add((project, meta.get('funded_by', '')))
261 projects = sorted(projects)
263 form = forms.SearchForm()
264 custom_pdf_form = forms.CustomPDFForm()
265 return render_to_response('catalogue/book_detail.html', locals(),
266 context_instance=RequestContext(request))
269 def book_text(request, book):
270 kwargs = models.Book.split_fileid(book)
273 book = get_object_or_404(models.Book, **kwargs)
275 if not book.has_html_file():
278 for fragment in book.fragments.all():
279 for theme in fragment.tags.filter(category='theme'):
280 book_themes.setdefault(theme, []).append(fragment)
282 book_themes = book_themes.items()
283 book_themes.sort(key=lambda s: s[0].sort_key)
284 return render_to_response('catalogue/book_text.html', locals(),
285 context_instance=RequestContext(request))
292 def _no_diacritics_regexp(query):
293 """ returns a regexp for searching for a query without diacritics
295 should be locale-aware """
297 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źżŹŻ',
298 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
302 return u"(%s)" % '|'.join(names[l])
303 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
305 def unicode_re_escape(query):
306 """ Unicode-friendly version of re.escape """
307 return re.sub('(?u)(\W)', r'\\\1', query)
309 def _word_starts_with(name, prefix):
310 """returns a Q object getting models having `name` contain a word
311 starting with `prefix`
313 We define word characters as alphanumeric and underscore, like in JS.
315 Works for MySQL, PostgreSQL, Oracle.
316 For SQLite, _sqlite* version is substituted for this.
320 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
321 # can't use [[:<:]] (word start),
322 # but we want both `xy` and `(xy` to catch `(xyz)`
323 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
328 def _word_starts_with_regexp(prefix):
329 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
330 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
333 def _sqlite_word_starts_with(name, prefix):
334 """ version of _word_starts_with for SQLite
336 SQLite in Django uses Python re module
339 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
343 if hasattr(settings, 'DATABASES'):
344 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
345 _word_starts_with = _sqlite_word_starts_with
346 elif settings.DATABASE_ENGINE == 'sqlite3':
347 _word_starts_with = _sqlite_word_starts_with
351 def __init__(self, name, view):
354 self.lower = name.lower()
355 self.category = 'application'
357 return reverse(*self._view)
360 App(u'Leśmianator', (u'lesmianator', )),
364 def _tags_starting_with(prefix, user=None):
365 prefix = prefix.lower()
367 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
368 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
370 books = models.Book.objects.filter(_word_starts_with('title', prefix))
371 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
372 if user and user.is_authenticated():
373 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
375 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
377 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
378 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
381 def _get_result_link(match, tag_list):
382 if isinstance(match, models.Tag):
383 return reverse('catalogue.views.tagged_object_list',
384 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
386 elif isinstance(match, App):
389 return match.get_absolute_url()
392 def _get_result_type(match):
393 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
396 type = match.category
400 def books_starting_with(prefix):
401 prefix = prefix.lower()
402 return models.Book.objects.filter(_word_starts_with('title', prefix))
405 def find_best_matches(query, user=None):
406 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
409 - zero elements when nothing is found,
410 - one element when a best result is found,
411 - more then one element on multiple exact matches
413 Raises a ValueError on too short a query.
416 query = query.lower()
418 raise ValueError("query must have at least two characters")
420 result = tuple(_tags_starting_with(query, user))
421 # remove pdcounter stuff
422 book_titles = set(match.pretty_title().lower() for match in result
423 if isinstance(match, models.Book))
424 authors = set(match.name.lower() for match in result
425 if isinstance(match, models.Tag) and match.category=='author')
426 result = tuple(res for res in result if not (
427 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
428 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
431 exact_matches = tuple(res for res in result if res.name.lower() == query)
435 return tuple(result)[:1]
439 tags = request.GET.get('tags', '')
440 prefix = request.GET.get('q', '')
443 tag_list = models.Tag.get_tag_list(tags)
448 result = find_best_matches(prefix, request.user)
450 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
451 context_instance=RequestContext(request))
454 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
455 elif len(result) > 1:
456 return render_to_response('catalogue/search_multiple_hits.html',
457 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
458 context_instance=RequestContext(request))
460 form = PublishingSuggestForm(initial={"books": prefix + ", "})
461 return render_to_response('catalogue/search_no_hits.html',
462 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
463 context_instance=RequestContext(request))
466 def tags_starting_with(request):
467 prefix = request.GET.get('q', '')
468 # Prefix must have at least 2 characters
470 return HttpResponse('')
473 for tag in _tags_starting_with(prefix, request.user):
474 if not tag.name in tags_list:
475 result += "\n" + tag.name
476 tags_list.append(tag.name)
477 return HttpResponse(result)
479 def json_tags_starting_with(request, callback=None):
481 prefix = request.GET.get('q', '')
482 callback = request.GET.get('callback', '')
483 # Prefix must have at least 2 characters
485 return HttpResponse('')
487 for tag in _tags_starting_with(prefix, request.user):
488 if not tag.name in tags_list:
489 tags_list.append(tag.name)
490 if request.GET.get('mozhint', ''):
491 result = [prefix, tags_list]
493 result = {"matches": tags_list}
494 return JSONResponse(result, callback)
496 # ====================
497 # = Shelf management =
498 # ====================
501 def user_shelves(request):
502 shelves = models.Tag.objects.filter(category='set', user=request.user)
503 new_set_form = forms.NewSetForm()
504 return render_to_response('catalogue/user_shelves.html', locals(),
505 context_instance=RequestContext(request))
508 def book_sets(request, book):
509 if not request.user.is_authenticated():
510 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
512 kwargs = models.Book.split_urlid(book)
515 book = get_object_or_404(models.Book, **kwargs)
517 user_sets = models.Tag.objects.filter(category='set', user=request.user)
518 book_sets = book.tags.filter(category='set', user=request.user)
520 if request.method == 'POST':
521 form = forms.ObjectSetsForm(book, request.user, request.POST)
523 old_shelves = list(book.tags.filter(category='set'))
524 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
526 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
527 shelf.book_count = None
530 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
531 shelf.book_count = None
534 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
535 if request.is_ajax():
536 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
538 return HttpResponseRedirect('/')
540 form = forms.ObjectSetsForm(book, request.user)
541 new_set_form = forms.NewSetForm()
543 return render_to_response('catalogue/book_sets.html', locals(),
544 context_instance=RequestContext(request))
550 def remove_from_shelf(request, shelf, book):
551 kwargs = models.Book.split_urlid(book)
554 book = get_object_or_404(models.Book, **kwargs)
556 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
558 if shelf in book.tags:
559 models.Tag.objects.remove_tag(book, shelf)
561 shelf.book_count = None
564 return HttpResponse(_('Book was successfully removed from the shelf'))
566 return HttpResponse(_('This book is not on the shelf'))
569 def collect_books(books):
571 Returns all real books in collection.
575 if len(book.children.all()) == 0:
578 result += collect_books(book.children.all())
583 def download_shelf(request, slug):
585 Create a ZIP archive on disk and transmit it in chunks of 8KB,
586 without loading the whole file into memory. A similar approach can
587 be used for large dynamic PDF files.
589 from slughifi import slughifi
593 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
596 form = forms.DownloadFormatsForm(request.GET)
598 formats = form.cleaned_data['formats']
599 if len(formats) == 0:
600 formats = ['pdf', 'epub', 'mobi', 'odt', 'txt']
602 # Create a ZIP archive
603 temp = tempfile.TemporaryFile()
604 archive = zipfile.ZipFile(temp, 'w')
607 for book in collect_books(models.Book.tagged.with_all(shelf)):
608 fileid = book.fileid()
609 if 'pdf' in formats and book.pdf_file:
610 filename = book.pdf_file.path
611 archive.write(filename, str('%s.pdf' % fileid))
612 if 'mobi' in formats and book.mobi_file:
613 filename = book.mobi_file.path
614 archive.write(filename, str('%s.mobi' % fileid))
615 if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
616 filename = book.root_ancestor.epub_file.path
617 archive.write(filename, str('%s.epub' % book.root_ancestor.fileid()))
618 already.add(book.root_ancestor)
619 if 'odt' in formats and book.has_media("odt"):
620 for file in book.get_media("odt"):
621 filename = file.file.path
622 archive.write(filename, str('%s.odt' % slughifi(file.name)))
623 if 'txt' in formats and book.txt_file:
624 filename = book.txt_file.path
625 archive.write(filename, str('%s.txt' % fileid))
628 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
629 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
630 response['Content-Length'] = temp.tell()
633 response.write(temp.read())
638 def shelf_book_formats(request, shelf):
640 Returns a list of formats of books in shelf.
642 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
644 formats = {'pdf': False, 'epub': False, 'mobi': False, 'odt': False, 'txt': False}
646 for book in collect_books(models.Book.tagged.with_all(shelf)):
648 formats['pdf'] = True
649 if book.root_ancestor.epub_file:
650 formats['epub'] = True
652 formats['mobi'] = True
654 formats['txt'] = True
655 for format in ('odt',):
656 if book.has_media(format):
657 formats[format] = True
659 return HttpResponse(LazyEncoder().encode(formats))
665 def new_set(request):
666 new_set_form = forms.NewSetForm(request.POST)
667 if new_set_form.is_valid():
668 new_set = new_set_form.save(request.user)
670 if request.is_ajax():
671 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
673 return HttpResponseRedirect('/')
675 return HttpResponseRedirect('/')
681 def delete_shelf(request, slug):
682 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
685 if request.is_ajax():
686 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
688 return HttpResponseRedirect('/')
697 form = AuthenticationForm(data=request.POST, prefix='login')
699 auth.login(request, form.get_user())
700 response_data = {'success': True, 'errors': {}}
702 response_data = {'success': False, 'errors': form.errors}
703 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
708 def register(request):
709 registration_form = UserCreationForm(request.POST, prefix='registration')
710 if registration_form.is_valid():
711 user = registration_form.save()
712 user = auth.authenticate(
713 username=registration_form.cleaned_data['username'],
714 password=registration_form.cleaned_data['password1']
716 auth.login(request, user)
717 response_data = {'success': True, 'errors': {}}
719 response_data = {'success': False, 'errors': registration_form.errors}
720 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
724 def logout_then_redirect(request):
726 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
735 def import_book(request):
736 """docstring for import_book"""
737 book_import_form = forms.BookImportForm(request.POST, request.FILES)
738 if book_import_form.is_valid():
740 book_import_form.save()
745 info = sys.exc_info()
746 exception = pprint.pformat(info[1])
747 tb = '\n'.join(traceback.format_tb(info[2]))
748 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
749 return HttpResponse(_("Book imported successfully"))
751 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
756 """ Provides server time for jquery.countdown,
757 in a format suitable for Date.parse()
759 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
764 def book_info(request, id, lang='pl'):
765 book = get_object_or_404(models.Book, id=id)
766 # set language by hand
767 translation.activate(lang)
768 return render_to_response('catalogue/book_info.html', locals(),
769 context_instance=RequestContext(request))
772 def tag_info(request, id):
773 tag = get_object_or_404(models.Tag, id=id)
774 return HttpResponse(tag.description)
777 def download_zip(request, format, book=None):
778 kwargs = models.Book.split_fileid(book)
781 if format in ('pdf', 'epub', 'mobi'):
782 url = models.Book.zip_format(format)
783 elif format == 'audiobook' and kwargs is not None:
784 book = get_object_or_404(models.Book, **kwargs)
785 url = book.zip_audiobooks()
787 raise Http404('No format specified for zip package')
788 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
791 def download_custom_pdf(request, book_fileid):
792 kwargs = models.Book.split_fileid(book_fileid)
795 book = get_object_or_404(models.Book, **kwargs)
797 if request.method == 'GET':
798 form = forms.CustomPDFForm(request.GET)
800 cust = form.customizations
801 pdf_file = models.get_customized_pdf_path(book, cust)
803 if not path.exists(pdf_file):
804 result = async_build_pdf.delay(book.id, cust, pdf_file)
806 return AttachmentHttpResponse(file_name=("%s.pdf" % book_fileid), file_path=pdf_file, mimetype="application/pdf")
808 raise Http404(_('Incorrect customization options for PDF'))
810 raise Http404(_('Bad method'))