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.
12 from django.conf import settings
13 from django.template import RequestContext
14 from django.shortcuts import render_to_response, get_object_or_404
15 from django.http import HttpResponse, HttpResponseRedirect, Http404
16 from django.core.urlresolvers import reverse
17 from django.db.models import Q
18 from django.contrib.auth.decorators import login_required, user_passes_test
19 from django.utils.datastructures import SortedDict
20 from django.views.decorators.http import require_POST
21 from django.contrib import auth
22 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
23 from django.utils import simplejson
24 from django.utils.functional import Promise
25 from django.utils.encoding import force_unicode
26 from django.utils.http import urlquote_plus
27 from django.views.decorators import cache
28 from django.utils.translation import ugettext as _
30 from catalogue import models
31 from catalogue import forms
32 from catalogue.utils import split_tags
33 from newtagging import views as newtagging_views
36 staff_required = user_passes_test(lambda user: user.is_staff)
39 class LazyEncoder(simplejson.JSONEncoder):
40 def default(self, obj):
41 if isinstance(obj, Promise):
42 return force_unicode(obj)
46 def main_page(request):
47 if request.user.is_authenticated():
48 shelves = models.Tag.objects.filter(category='set', user=request.user)
49 new_set_form = forms.NewSetForm()
50 extra_where = "NOT catalogue_tag.category = 'set'"
51 tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
52 fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
53 extra={'where': ["catalogue_tag.category = 'theme'"] + [extra_where]})
54 categories = split_tags(tags)
56 form = forms.SearchForm()
57 return render_to_response('catalogue/main_page.html', locals(),
58 context_instance=RequestContext(request))
61 def book_list(request):
62 books = models.Book.objects.all()
63 form = forms.SearchForm()
65 books_by_first_letter = SortedDict()
67 books_by_first_letter.setdefault(book.title[0], []).append(book)
69 return render_to_response('catalogue/book_list.html', locals(),
70 context_instance=RequestContext(request))
73 def tagged_object_list(request, tags=''):
74 # Prevent DoS attacks on our database
75 if len(tags.split('/')) > 6:
79 tags = models.Tag.get_tag_list(tags)
80 except models.Tag.DoesNotExist:
83 if len([tag for tag in tags if tag.category == 'book']):
87 shelf = [tag for tag in tags if tag.category == 'set']
88 shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
89 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
91 model = models.Fragment
92 only_author = len(tags) == 1 and tags[0].category == 'author'
93 pd_counter = only_author and tags[0].goes_to_pd()
95 user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
97 extra_where = "catalogue_tag.category NOT IN ('set', 'book')"
98 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
99 categories = split_tags(related_tags)
101 if not (theme_is_set or shelf_is_set):
102 model=models.Book.objects.filter(parent=None)
104 return newtagging_views.tagged_object_list(
106 tag_model=models.Tag,
107 queryset_or_model=model,
109 template_name='catalogue/tagged_object_list.html',
111 'categories': categories,
112 'shelf_is_set': shelf_is_set,
113 'only_author': only_author,
114 'pd_counter': pd_counter,
115 'user_is_owner': user_is_owner,
116 'formats_form': forms.DownloadFormatsForm(),
121 def book_fragments(request, book_slug, theme_slug):
122 book = get_object_or_404(models.Book, slug=book_slug)
123 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
124 theme = get_object_or_404(models.Tag, slug=theme_slug)
125 fragments = models.Fragment.tagged.with_all([book_tag, theme])
127 form = forms.SearchForm()
128 return render_to_response('catalogue/book_fragments.html', locals(),
129 context_instance=RequestContext(request))
132 def book_detail(request, slug):
134 book = models.Book.objects.get(slug=slug)
135 except models.Book.DoesNotExist:
136 return book_stub_detail(request, slug)
138 book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
139 tags = list(book.tags.filter(~Q(category='set')))
140 categories = split_tags(tags)
141 book_children = book.children.all().order_by('parent_number')
142 extra_where = "catalogue_tag.category = 'theme'"
143 book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
144 extra_info = book.get_extra_info_value()
146 form = forms.SearchForm()
147 return render_to_response('catalogue/book_detail.html', locals(),
148 context_instance=RequestContext(request))
151 def book_stub_detail(request, slug):
152 book = get_object_or_404(models.BookStub, slug=slug)
154 form = forms.SearchForm()
156 return render_to_response('catalogue/book_stub_detail.html', locals(),
157 context_instance=RequestContext(request))
160 def book_text(request, slug):
161 book = get_object_or_404(models.Book, slug=slug)
163 for fragment in book.fragments.all():
164 for theme in fragment.tags.filter(category='theme'):
165 book_themes.setdefault(theme, []).append(fragment)
167 book_themes = book_themes.items()
168 book_themes.sort(key=lambda s: s[0].sort_key)
169 return render_to_response('catalogue/book_text.html', locals(),
170 context_instance=RequestContext(request))
177 def _no_diacritics_regexp(query):
178 """ returns a regexp for searching for a query without diacritics
180 should be locale-aware """
181 names = {'a':u'ą', 'c':u'ć', 'e':u'ę', 'l': u'ł', 'n':u'ń', 'o':u'ó', 's':u'ś', 'z':u'ź|ż'}
184 return "(%s|%s)" % (l, names[l])
185 return re.sub('[%s]'%(''.join(names.keys())), repl, query)
187 def _word_starts_with(name, prefix):
188 """returns a Q object getting models having `name` contain a word
189 starting with `prefix`
192 if settings.DATABASE_ENGINE in ('mysql', 'postgresql_psycopg2', 'postgresql'):
193 prefix = _no_diacritics_regexp(re.escape(prefix))
194 # we could use a [[:<:]] (word start),
195 # but we want both `xy` and `(xy` to catch `(xyz)`
196 kwargs['%s__iregex' % name] = u"(^|[^[:alpha:]])%s" % prefix
198 # don't know how to do a generic regex
199 # checking for simple icontain instead
200 kwargs['%s__icontains' % name] = prefix
204 def _tags_exact_matches(prefix, user):
205 book_stubs = models.BookStub.objects.filter(title__iexact = prefix)
206 books = models.Book.objects.filter(title__iexact = prefix)
207 book_stubs = filter(lambda x: x not in books, book_stubs)
208 tags = models.Tag.objects.filter(name__iexact = prefix)
209 if user.is_authenticated():
210 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
212 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
214 return list(books) + list(tags) + list(book_stubs)
217 def _tags_starting_with(prefix, user):
218 book_stubs = models.BookStub.objects.filter(_word_starts_with('title', prefix))
219 books = models.Book.objects.filter(_word_starts_with('title', prefix))
220 book_stubs = filter(lambda x: x not in books, book_stubs)
221 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
222 if user.is_authenticated():
223 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
225 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
227 return list(books) + list(tags) + list(book_stubs)
231 def _get_result_link(match, tag_list):
232 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
233 return match.get_absolute_url()
235 return reverse('catalogue.views.tagged_object_list',
236 kwargs={'tags': '/'.join(tag.slug for tag in tag_list + [match])}
239 def _get_result_type(match):
240 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
243 type = match.category
244 return dict(models.TAG_CATEGORIES)[type]
249 tags = request.GET.get('tags', '')
250 prefix = request.GET.get('q', '')
253 tag_list = models.Tag.get_tag_list(tags)
257 # Prefix must have at least 2 characters
259 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
260 context_instance=RequestContext(request))
262 result = _tags_exact_matches(prefix, request.user)
265 # multiple exact matches
266 return render_to_response('catalogue/search_multiple_hits.html',
267 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
268 context_instance=RequestContext(request))
272 result = _tags_starting_with(prefix, request.user)
275 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
277 return render_to_response('catalogue/search_no_hits.html', {'tags':tag_list, 'prefix':prefix},
278 context_instance=RequestContext(request))
281 def tags_starting_with(request):
282 prefix = request.GET.get('q', '')
283 # Prefix must have at least 2 characters
285 return HttpResponse('')
287 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
290 # ====================
291 # = Shelf management =
292 # ====================
295 def user_shelves(request):
296 shelves = models.Tag.objects.filter(category='set', user=request.user)
297 new_set_form = forms.NewSetForm()
298 return render_to_response('catalogue/user_shelves.html', locals(),
299 context_instance=RequestContext(request))
302 def book_sets(request, slug):
303 book = get_object_or_404(models.Book, slug=slug)
304 user_sets = models.Tag.objects.filter(category='set', user=request.user)
305 book_sets = book.tags.filter(category='set', user=request.user)
307 if not request.user.is_authenticated():
308 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
310 if request.method == 'POST':
311 form = forms.ObjectSetsForm(book, request.user, request.POST)
313 old_shelves = list(book.tags.filter(category='set'))
314 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
316 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
317 shelf.book_count -= 1
320 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
321 shelf.book_count += 1
324 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
325 if request.is_ajax():
326 return HttpResponse(_('<p>Shelves were sucessfully saved.</p>'))
328 return HttpResponseRedirect('/')
330 form = forms.ObjectSetsForm(book, request.user)
331 new_set_form = forms.NewSetForm()
333 return render_to_response('catalogue/book_sets.html', locals(),
334 context_instance=RequestContext(request))
340 def remove_from_shelf(request, shelf, book):
341 book = get_object_or_404(models.Book, slug=book)
342 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
344 if shelf in book.tags:
345 models.Tag.objects.remove_tag(book, shelf)
347 shelf.book_count -= 1
350 return HttpResponse(_('Book was successfully removed from the shelf'))
352 return HttpResponse(_('This book is not on the shelf'))
355 def collect_books(books):
357 Returns all real books in collection.
361 if len(book.children.all()) == 0:
364 result += collect_books(book.children.all())
369 def download_shelf(request, slug):
371 Create a ZIP archive on disk and transmit it in chunks of 8KB,
372 without loading the whole file into memory. A similar approach can
373 be used for large dynamic PDF files.
375 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
378 form = forms.DownloadFormatsForm(request.GET)
380 formats = form.cleaned_data['formats']
381 if len(formats) == 0:
382 formats = ['pdf', 'odt', 'txt', 'mp3', 'ogg']
384 # Create a ZIP archive
385 temp = tempfile.TemporaryFile()
386 archive = zipfile.ZipFile(temp, 'w')
388 for book in collect_books(models.Book.tagged.with_all(shelf)):
389 if 'pdf' in formats and book.pdf_file:
390 filename = book.pdf_file.path
391 archive.write(filename, str('%s.pdf' % book.slug))
392 if 'odt' in formats and book.odt_file:
393 filename = book.odt_file.path
394 archive.write(filename, str('%s.odt' % book.slug))
395 if 'txt' in formats and book.txt_file:
396 filename = book.txt_file.path
397 archive.write(filename, str('%s.txt' % book.slug))
398 if 'mp3' in formats and book.mp3_file:
399 filename = book.mp3_file.path
400 archive.write(filename, str('%s.mp3' % book.slug))
401 if 'ogg' in formats and book.ogg_file:
402 filename = book.ogg_file.path
403 archive.write(filename, str('%s.ogg' % book.slug))
406 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
407 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
408 response['Content-Length'] = temp.tell()
411 response.write(temp.read())
416 def shelf_book_formats(request, shelf):
418 Returns a list of formats of books in shelf.
420 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
422 formats = {'pdf': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
424 for book in collect_books(models.Book.tagged.with_all(shelf)):
426 formats['pdf'] = True
428 formats['odt'] = True
430 formats['txt'] = True
432 formats['mp3'] = True
434 formats['ogg'] = True
436 return HttpResponse(LazyEncoder().encode(formats))
442 def new_set(request):
443 new_set_form = forms.NewSetForm(request.POST)
444 if new_set_form.is_valid():
445 new_set = new_set_form.save(request.user)
447 if request.is_ajax():
448 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully created</p>') % new_set)
450 return HttpResponseRedirect('/')
452 return HttpResponseRedirect('/')
458 def delete_shelf(request, slug):
459 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
462 if request.is_ajax():
463 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
465 return HttpResponseRedirect('/')
474 form = AuthenticationForm(data=request.POST, prefix='login')
476 auth.login(request, form.get_user())
477 response_data = {'success': True, 'errors': {}}
479 response_data = {'success': False, 'errors': form.errors}
480 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
485 def register(request):
486 registration_form = UserCreationForm(request.POST, prefix='registration')
487 if registration_form.is_valid():
488 user = registration_form.save()
489 user = auth.authenticate(
490 username=registration_form.cleaned_data['username'],
491 password=registration_form.cleaned_data['password1']
493 auth.login(request, user)
494 response_data = {'success': True, 'errors': {}}
496 response_data = {'success': False, 'errors': registration_form.errors}
497 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
501 def logout_then_redirect(request):
503 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
512 def import_book(request):
513 """docstring for import_book"""
514 book_import_form = forms.BookImportForm(request.POST, request.FILES)
515 if book_import_form.is_valid():
517 book_import_form.save()
519 info = sys.exc_info()
520 exception = pprint.pformat(info[1])
521 tb = '\n'.join(traceback.format_tb(info[2]))
522 return HttpResponse(_("An error occurred: %s\n\n%s") % (exception, tb), mimetype='text/plain')
523 return HttpResponse(_("Book imported successfully"))
525 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
530 """ Provides server time for jquery.countdown,
531 in a format suitable for Date.parse()
533 from datetime import datetime
534 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))