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