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