merge picture to pretty
[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 catalogue.tasks import touch_tag
33 from pdcounter import models as pdcounter_models
34 from pdcounter import views as pdcounter_views
35 from suggest.forms import PublishingSuggestForm
36
37 from os import path
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 catalogue(request):
60     tags = models.Tag.objects.exclude(
61         category__in=('set', 'book')).exclude(book_count=0)
62     tags = list(tags)
63     for tag in tags:
64         tag.count = tag.book_count
65     categories = split_tags(tags)
66     fragment_tags = categories.get('theme', [])
67
68     form = forms.SearchForm()
69     return render_to_response('catalogue/catalogue.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, theme_slug):
207     kwargs = models.Book.split_urlid(book)
208     if kwargs is None:
209         raise Http404
210     book = get_object_or_404(models.Book, **kwargs)
211
212     book_tag = book.book_tag()
213     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
214     fragments = models.Fragment.tagged.with_all([book_tag, theme])
215
216     form = forms.SearchForm()
217     return render_to_response('catalogue/book_fragments.html', locals(),
218         context_instance=RequestContext(request))
219
220
221 def book_detail(request, book):
222     kwargs = models.Book.split_urlid(book)
223     if kwargs is None:
224         raise Http404
225     try:
226         book = models.Book.objects.get(**kwargs)
227     except models.Book.DoesNotExist:
228         return pdcounter_views.book_stub_detail(request, kwargs['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', 'sort_key')
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     hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
249
250     projects = set()
251     for m in book.media.filter(type='mp3'):
252         # ogg files are always from the same project
253         meta = m.get_extra_info_value()
254         project = meta.get('project')
255         if not project:
256             # temporary fallback
257             project = u'CzytamySłuchając'
258
259         projects.add((project, meta.get('funded_by', '')))
260     projects = sorted(projects)
261
262     form = forms.SearchForm()
263     custom_pdf_form = forms.CustomPDFForm()
264     return render_to_response('catalogue/book_detail.html', locals(),
265         context_instance=RequestContext(request))
266
267
268 def book_text(request, book):
269     kwargs = models.Book.split_fileid(book)
270     if kwargs is None:
271         raise Http404
272     book = get_object_or_404(models.Book, **kwargs)
273
274     if not book.has_html_file():
275         raise Http404
276     book_themes = {}
277     for fragment in book.fragments.all():
278         for theme in fragment.tags.filter(category='theme'):
279             book_themes.setdefault(theme, []).append(fragment)
280
281     book_themes = book_themes.items()
282     book_themes.sort(key=lambda s: s[0].sort_key)
283     return render_to_response('catalogue/book_text.html', locals(),
284         context_instance=RequestContext(request))
285
286
287 # ==========
288 # = Search =
289 # ==========
290
291 def _no_diacritics_regexp(query):
292     """ returns a regexp for searching for a query without diacritics
293
294     should be locale-aware """
295     names = {
296         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źżŹŻ',
297         u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
298         }
299     def repl(m):
300         l = m.group()
301         return u"(%s)" % '|'.join(names[l])
302     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
303
304 def unicode_re_escape(query):
305     """ Unicode-friendly version of re.escape """
306     return re.sub('(?u)(\W)', r'\\\1', query)
307
308 def _word_starts_with(name, prefix):
309     """returns a Q object getting models having `name` contain a word
310     starting with `prefix`
311
312     We define word characters as alphanumeric and underscore, like in JS.
313
314     Works for MySQL, PostgreSQL, Oracle.
315     For SQLite, _sqlite* version is substituted for this.
316     """
317     kwargs = {}
318
319     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
320     # can't use [[:<:]] (word start),
321     # but we want both `xy` and `(xy` to catch `(xyz)`
322     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
323
324     return Q(**kwargs)
325
326
327 def _word_starts_with_regexp(prefix):
328     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
329     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
330
331
332 def _sqlite_word_starts_with(name, prefix):
333     """ version of _word_starts_with for SQLite
334
335     SQLite in Django uses Python re module
336     """
337     kwargs = {}
338     kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
339     return Q(**kwargs)
340
341
342 if hasattr(settings, 'DATABASES'):
343     if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
344         _word_starts_with = _sqlite_word_starts_with
345 elif settings.DATABASE_ENGINE == 'sqlite3':
346     _word_starts_with = _sqlite_word_starts_with
347
348
349 class App():
350     def __init__(self, name, view):
351         self.name = name
352         self._view = view
353         self.lower = name.lower()
354         self.category = 'application'
355     def view(self):
356         return reverse(*self._view)
357
358 _apps = (
359     App(u'Leśmianator', (u'lesmianator', )),
360     )
361
362
363 def _tags_starting_with(prefix, user=None):
364     prefix = prefix.lower()
365     # PD counter
366     book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
367     authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
368
369     books = models.Book.objects.filter(_word_starts_with('title', prefix))
370     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
371     if user and user.is_authenticated():
372         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
373     else:
374         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
375
376     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
377     return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
378
379
380 def _get_result_link(match, tag_list):
381     if isinstance(match, models.Tag):
382         return reverse('catalogue.views.tagged_object_list',
383             kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
384         )
385     elif isinstance(match, App):
386         return match.view()
387     else:
388         return match.get_absolute_url()
389
390
391 def _get_result_type(match):
392     if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
393         type = 'book'
394     else:
395         type = match.category
396     return type
397
398
399 def books_starting_with(prefix):
400     prefix = prefix.lower()
401     return models.Book.objects.filter(_word_starts_with('title', prefix))
402
403
404 def find_best_matches(query, user=None):
405     """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
406
407     Returns a with:
408       - zero elements when nothing is found,
409       - one element when a best result is found,
410       - more then one element on multiple exact matches
411
412     Raises a ValueError on too short a query.
413     """
414
415     query = query.lower()
416     if len(query) < 2:
417         raise ValueError("query must have at least two characters")
418
419     result = tuple(_tags_starting_with(query, user))
420     # remove pdcounter stuff
421     book_titles = set(match.pretty_title().lower() for match in result
422                       if isinstance(match, models.Book))
423     authors = set(match.name.lower() for match in result
424                   if isinstance(match, models.Tag) and match.category=='author')
425     result = tuple(res for res in result if not (
426                  (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
427                  or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
428              ))
429
430     exact_matches = tuple(res for res in result if res.name.lower() == query)
431     if exact_matches:
432         return exact_matches
433     else:
434         return tuple(result)[:1]
435
436
437 def search(request):
438     tags = request.GET.get('tags', '')
439     prefix = request.GET.get('q', '')
440
441     try:
442         tag_list = models.Tag.get_tag_list(tags)
443     except:
444         tag_list = []
445
446     try:
447         result = find_best_matches(prefix, request.user)
448     except ValueError:
449         return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
450             context_instance=RequestContext(request))
451
452     if len(result) == 1:
453         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
454     elif len(result) > 1:
455         return render_to_response('catalogue/search_multiple_hits.html',
456             {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
457             context_instance=RequestContext(request))
458     else:
459         form = PublishingSuggestForm(initial={"books": prefix + ", "})
460         return render_to_response('catalogue/search_no_hits.html', 
461             {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
462             context_instance=RequestContext(request))
463
464
465 def tags_starting_with(request):
466     prefix = request.GET.get('q', '')
467     # Prefix must have at least 2 characters
468     if len(prefix) < 2:
469         return HttpResponse('')
470     tags_list = []
471     result = ""   
472     for tag in _tags_starting_with(prefix, request.user):
473         if not tag.name in tags_list:
474             result += "\n" + tag.name
475             tags_list.append(tag.name)
476     return HttpResponse(result)
477
478 def json_tags_starting_with(request, callback=None):
479     # Callback for JSONP
480     prefix = request.GET.get('q', '')
481     callback = request.GET.get('callback', '')
482     # Prefix must have at least 2 characters
483     if len(prefix) < 2:
484         return HttpResponse('')
485     tags_list = []
486     for tag in _tags_starting_with(prefix, request.user):
487         if not tag.name in tags_list:
488             tags_list.append(tag.name)
489     if request.GET.get('mozhint', ''):
490         result = [prefix, tags_list]
491     else:
492         result = {"matches": tags_list}
493     return JSONResponse(result, callback)
494
495 # ====================
496 # = Shelf management =
497 # ====================
498 @login_required
499 @cache.never_cache
500 def user_shelves(request):
501     shelves = models.Tag.objects.filter(category='set', user=request.user)
502     new_set_form = forms.NewSetForm()
503     return render_to_response('catalogue/user_shelves.html', locals(),
504             context_instance=RequestContext(request))
505
506 @cache.never_cache
507 def book_sets(request, book):
508     if not request.user.is_authenticated():
509         return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
510
511     kwargs = models.Book.split_urlid(book)
512     if kwargs is None:
513         raise Http404
514     book = get_object_or_404(models.Book, **kwargs)
515
516     user_sets = models.Tag.objects.filter(category='set', user=request.user)
517     book_sets = book.tags.filter(category='set', user=request.user)
518
519     if request.method == 'POST':
520         form = forms.ObjectSetsForm(book, request.user, request.POST)
521         if form.is_valid():
522             old_shelves = list(book.tags.filter(category='set'))
523             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
524
525             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
526                 touch_tag(shelf)
527
528             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
529                 touch_tag(shelf)
530
531             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
532             if request.is_ajax():
533                 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
534             else:
535                 return HttpResponseRedirect('/')
536     else:
537         form = forms.ObjectSetsForm(book, request.user)
538         new_set_form = forms.NewSetForm()
539
540     return render_to_response('catalogue/book_sets.html', locals(),
541         context_instance=RequestContext(request))
542
543
544 @login_required
545 @require_POST
546 @cache.never_cache
547 def remove_from_shelf(request, shelf, book):
548     kwargs = models.Book.split_urlid(book)
549     if kwargs is None:
550         raise Http404
551     book = get_object_or_404(models.Book, **kwargs)
552
553     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
554
555     if shelf in book.tags:
556         models.Tag.objects.remove_tag(book, shelf)
557         touch_tag(shelf)
558
559         return HttpResponse(_('Book was successfully removed from the shelf'))
560     else:
561         return HttpResponse(_('This book is not on the shelf'))
562
563
564 def collect_books(books):
565     """
566     Returns all real books in collection.
567     """
568     result = []
569     for book in books:
570         if len(book.children.all()) == 0:
571             result.append(book)
572         else:
573             result += collect_books(book.children.all())
574     return result
575
576
577 @cache.never_cache
578 def download_shelf(request, slug):
579     """"
580     Create a ZIP archive on disk and transmit it in chunks of 8KB,
581     without loading the whole file into memory. A similar approach can
582     be used for large dynamic PDF files.
583     """
584     from slughifi import slughifi
585     import tempfile
586     import zipfile
587
588     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
589
590     formats = []
591     form = forms.DownloadFormatsForm(request.GET)
592     if form.is_valid():
593         formats = form.cleaned_data['formats']
594     if len(formats) == 0:
595         formats = models.Book.ebook_formats
596
597     # Create a ZIP archive
598     temp = tempfile.TemporaryFile()
599     archive = zipfile.ZipFile(temp, 'w')
600
601     for book in collect_books(models.Book.tagged.with_all(shelf)):
602         fileid = book.fileid()
603         for ebook_format in models.Book.ebook_formats:
604             if ebook_format in formats and book.has_media(ebook_format):
605                 filename = book.get_media(ebook_format).path
606                 archive.write(filename, str('%s.%s' % (fileid, ebook_format)))
607     archive.close()
608
609     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
610     response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
611     response['Content-Length'] = temp.tell()
612
613     temp.seek(0)
614     response.write(temp.read())
615     return response
616
617
618 @cache.never_cache
619 def shelf_book_formats(request, shelf):
620     """"
621     Returns a list of formats of books in shelf.
622     """
623     shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
624
625     formats = {}
626     for ebook_format in models.Book.ebook_formats:
627         formats[ebook_format] = False
628
629     for book in collect_books(models.Book.tagged.with_all(shelf)):
630         for ebook_format in models.Book.ebook_formats:
631             if book.has_media(ebook_format):
632                 formats[ebook_format] = True
633
634     return HttpResponse(LazyEncoder().encode(formats))
635
636
637 @login_required
638 @require_POST
639 @cache.never_cache
640 def new_set(request):
641     new_set_form = forms.NewSetForm(request.POST)
642     if new_set_form.is_valid():
643         new_set = new_set_form.save(request.user)
644
645         if request.is_ajax():
646             return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
647         else:
648             return HttpResponseRedirect('/')
649
650     return HttpResponseRedirect('/')
651
652
653 @login_required
654 @require_POST
655 @cache.never_cache
656 def delete_shelf(request, slug):
657     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
658     user_set.delete()
659
660     if request.is_ajax():
661         return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
662     else:
663         return HttpResponseRedirect('/')
664
665
666 # ==================
667 # = Authentication =
668 # ==================
669 @require_POST
670 @cache.never_cache
671 def login(request):
672     form = AuthenticationForm(data=request.POST, prefix='login')
673     if form.is_valid():
674         auth.login(request, form.get_user())
675         response_data = {'success': True, 'errors': {}}
676     else:
677         response_data = {'success': False, 'errors': form.errors}
678     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
679
680
681 @require_POST
682 @cache.never_cache
683 def register(request):
684     registration_form = UserCreationForm(request.POST, prefix='registration')
685     if registration_form.is_valid():
686         user = registration_form.save()
687         user = auth.authenticate(
688             username=registration_form.cleaned_data['username'],
689             password=registration_form.cleaned_data['password1']
690         )
691         auth.login(request, user)
692         response_data = {'success': True, 'errors': {}}
693     else:
694         response_data = {'success': False, 'errors': registration_form.errors}
695     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
696
697
698 @cache.never_cache
699 def logout_then_redirect(request):
700     auth.logout(request)
701     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
702
703
704
705 # =========
706 # = Admin =
707 # =========
708 @login_required
709 @staff_required
710 def import_book(request):
711     """docstring for import_book"""
712     book_import_form = forms.BookImportForm(request.POST, request.FILES)
713     if book_import_form.is_valid():
714         try:
715             book_import_form.save()
716         except:
717             import sys
718             import pprint
719             import traceback
720             info = sys.exc_info()
721             exception = pprint.pformat(info[1])
722             tb = '\n'.join(traceback.format_tb(info[2]))
723             return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
724         return HttpResponse(_("Book imported successfully"))
725     else:
726         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
727
728
729
730 def clock(request):
731     """ Provides server time for jquery.countdown,
732     in a format suitable for Date.parse()
733     """
734     return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
735
736
737 # info views for API
738
739 def book_info(request, id, lang='pl'):
740     book = get_object_or_404(models.Book, id=id)
741     # set language by hand
742     translation.activate(lang)
743     return render_to_response('catalogue/book_info.html', locals(),
744         context_instance=RequestContext(request))
745
746
747 def tag_info(request, id):
748     tag = get_object_or_404(models.Tag, id=id)
749     return HttpResponse(tag.description)
750
751
752 def download_zip(request, format, book=None):
753     kwargs = models.Book.split_fileid(book)
754
755     url = None
756     if format in models.Book.ebook_formats:
757         url = models.Book.zip_format(format)
758     elif format == 'audiobook' and kwargs is not None:
759         book = get_object_or_404(models.Book, **kwargs)
760         url = book.zip_audiobooks()
761     else:
762         raise Http404('No format specified for zip package')
763     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
764
765
766 def download_custom_pdf(request, book_fileid):
767     kwargs = models.Book.split_fileid(book_fileid)
768     if kwargs is None:
769         raise Http404
770     book = get_object_or_404(models.Book, **kwargs)
771
772     if request.method == 'GET':
773         form = forms.CustomPDFForm(request.GET)
774         if form.is_valid():
775             cust = form.customizations
776             pdf_file = models.get_customized_pdf_path(book, cust)
777                 
778             if not path.exists(pdf_file):
779                 result = async_build_pdf.delay(book.id, cust, pdf_file)
780                 result.wait()
781             return AttachmentHttpResponse(file_name=("%s.pdf" % book_fileid), file_path=pdf_file, mimetype="application/pdf")
782         else:
783             raise Http404(_('Incorrect customization options for PDF'))
784     else:
785         raise Http404(_('Bad method'))