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