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