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