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