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