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