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 my_shelf_is_set = shelf_is_set and tags[0].user == request.user
90 theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
92 model = models.Fragment
93 only_author = len(tags) == 1 and tags[0].category == 'author'
94 pd_counter = only_author and tags[0].goes_to_pd()
96 user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
98 extra_where = "catalogue_tag.category NOT IN ('set', 'book')"
99 related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
100 categories = split_tags(related_tags)
102 if not (theme_is_set or shelf_is_set):
103 model=models.Book.objects.filter(parent=None)
105 return newtagging_views.tagged_object_list(
107 tag_model=models.Tag,
108 queryset_or_model=model,
110 template_name='catalogue/tagged_object_list.html',
112 'categories': categories,
113 'shelf_is_set': shelf_is_set,
114 'my_shelf_is_set': my_shelf_is_set,
115 'only_author': only_author,
116 'pd_counter': pd_counter,
117 'user_is_owner': user_is_owner,
118 'formats_form': forms.DownloadFormatsForm(),
123 def book_fragments(request, book_slug, theme_slug):
124 book = get_object_or_404(models.Book, slug=book_slug)
125 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug)
126 theme = get_object_or_404(models.Tag, slug=theme_slug)
127 fragments = models.Fragment.tagged.with_all([book_tag, theme])
129 form = forms.SearchForm()
130 return render_to_response('catalogue/book_fragments.html', locals(),
131 context_instance=RequestContext(request))
134 def book_detail(request, slug):
136 book = models.Book.objects.get(slug=slug)
137 except models.Book.DoesNotExist:
138 return book_stub_detail(request, slug)
140 book_tag = get_object_or_404(models.Tag, slug = 'l-' + slug)
141 tags = list(book.tags.filter(~Q(category='set')))
142 categories = split_tags(tags)
143 book_children = book.children.all().order_by('parent_number')
144 extra_where = "catalogue_tag.category = 'theme'"
145 book_themes = models.Tag.objects.related_for_model(book_tag, models.Fragment, counts=True, extra={'where': [extra_where]})
146 extra_info = book.get_extra_info_value()
148 form = forms.SearchForm()
149 return render_to_response('catalogue/book_detail.html', locals(),
150 context_instance=RequestContext(request))
153 def book_stub_detail(request, slug):
154 book = get_object_or_404(models.BookStub, slug=slug)
156 form = forms.SearchForm()
158 return render_to_response('catalogue/book_stub_detail.html', locals(),
159 context_instance=RequestContext(request))
162 def book_text(request, slug):
163 book = get_object_or_404(models.Book, slug=slug)
165 for fragment in book.fragments.all():
166 for theme in fragment.tags.filter(category='theme'):
167 book_themes.setdefault(theme, []).append(fragment)
169 book_themes = book_themes.items()
170 book_themes.sort(key=lambda s: s[0].sort_key)
171 return render_to_response('catalogue/book_text.html', locals(),
172 context_instance=RequestContext(request))
179 def _no_diacritics_regexp(query):
180 """ returns a regexp for searching for a query without diacritics
182 should be locale-aware """
183 names = {'a':u'ą', 'c':u'ć', 'e':u'ę', 'l': u'ł', 'n':u'ń', 'o':u'ó', 's':u'ś', 'z':u'ź|ż'}
186 return "(%s|%s)" % (l, names[l])
187 return re.sub('[%s]'%(''.join(names.keys())), repl, query)
189 def _word_starts_with(name, prefix):
190 """returns a Q object getting models having `name` contain a word
191 starting with `prefix`
194 if settings.DATABASE_ENGINE in ('mysql', 'postgresql_psycopg2', 'postgresql'):
195 prefix = _no_diacritics_regexp(re.escape(prefix))
196 # we could use a [[:<:]] (word start),
197 # but we want both `xy` and `(xy` to catch `(xyz)`
198 kwargs['%s__iregex' % name] = u"(^|[^[:alpha:]])%s" % prefix
200 # don't know how to do a generic regex
201 # checking for simple icontain instead
202 kwargs['%s__icontains' % name] = prefix
206 def _tags_exact_matches(prefix, user):
207 book_stubs = models.BookStub.objects.filter(title__iexact = prefix)
208 books = models.Book.objects.filter(title__iexact = prefix)
209 book_stubs = filter(lambda x: x not in books, book_stubs)
210 tags = models.Tag.objects.filter(name__iexact = prefix)
211 if user.is_authenticated():
212 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
214 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
216 return list(books) + list(tags) + list(book_stubs)
219 def _tags_starting_with(prefix, user):
220 book_stubs = models.BookStub.objects.filter(_word_starts_with('title', prefix))
221 books = models.Book.objects.filter(_word_starts_with('title', prefix))
222 book_stubs = filter(lambda x: x not in books, book_stubs)
223 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
224 if user.is_authenticated():
225 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
227 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
229 return list(books) + list(tags) + list(book_stubs)
233 def _get_result_link(match, tag_list):
234 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
235 return match.get_absolute_url()
237 return reverse('catalogue.views.tagged_object_list',
238 kwargs={'tags': '/'.join(tag.slug for tag in tag_list + [match])}
241 def _get_result_type(match):
242 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
245 type = match.category
246 return dict(models.TAG_CATEGORIES)[type]
251 tags = request.GET.get('tags', '')
252 prefix = request.GET.get('q', '')
255 tag_list = models.Tag.get_tag_list(tags)
259 # Prefix must have at least 2 characters
261 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
262 context_instance=RequestContext(request))
264 result = _tags_exact_matches(prefix, request.user)
267 # multiple exact matches
268 return render_to_response('catalogue/search_multiple_hits.html',
269 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
270 context_instance=RequestContext(request))
274 result = _tags_starting_with(prefix, request.user)
277 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
279 return render_to_response('catalogue/search_no_hits.html', {'tags':tag_list, 'prefix':prefix},
280 context_instance=RequestContext(request))
283 def tags_starting_with(request):
284 prefix = request.GET.get('q', '')
285 # Prefix must have at least 2 characters
287 return HttpResponse('')
289 return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
292 # ====================
293 # = Shelf management =
294 # ====================
297 def user_shelves(request):
298 shelves = models.Tag.objects.filter(category='set', user=request.user)
299 new_set_form = forms.NewSetForm()
300 return render_to_response('catalogue/user_shelves.html', locals(),
301 context_instance=RequestContext(request))
304 def book_sets(request, slug):
305 book = get_object_or_404(models.Book, slug=slug)
306 user_sets = models.Tag.objects.filter(category='set', user=request.user)
307 book_sets = book.tags.filter(category='set', user=request.user)
309 if not request.user.is_authenticated():
310 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
312 if request.method == 'POST':
313 form = forms.ObjectSetsForm(book, request.user, request.POST)
315 old_shelves = list(book.tags.filter(category='set'))
316 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
318 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
319 shelf.book_count -= 1
322 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
323 shelf.book_count += 1
326 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
327 if request.is_ajax():
328 return HttpResponse(_('<p>Shelves were sucessfully saved.</p>'))
330 return HttpResponseRedirect('/')
332 form = forms.ObjectSetsForm(book, request.user)
333 new_set_form = forms.NewSetForm()
335 return render_to_response('catalogue/book_sets.html', locals(),
336 context_instance=RequestContext(request))
342 def remove_from_shelf(request, shelf, book):
343 book = get_object_or_404(models.Book, slug=book)
344 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
346 if shelf in book.tags:
347 models.Tag.objects.remove_tag(book, shelf)
349 shelf.book_count -= 1
352 return HttpResponse(_('Book was successfully removed from the shelf'))
354 return HttpResponse(_('This book is not on the shelf'))
357 def collect_books(books):
359 Returns all real books in collection.
363 if len(book.children.all()) == 0:
366 result += collect_books(book.children.all())
371 def download_shelf(request, slug):
373 Create a ZIP archive on disk and transmit it in chunks of 8KB,
374 without loading the whole file into memory. A similar approach can
375 be used for large dynamic PDF files.
377 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
380 form = forms.DownloadFormatsForm(request.GET)
382 formats = form.cleaned_data['formats']
383 if len(formats) == 0:
384 formats = ['pdf', 'odt', 'txt', 'mp3', 'ogg']
386 # Create a ZIP archive
387 temp = tempfile.TemporaryFile()
388 archive = zipfile.ZipFile(temp, 'w')
390 for book in collect_books(models.Book.tagged.with_all(shelf)):
391 if 'pdf' in formats and book.pdf_file:
392 filename = book.pdf_file.path
393 archive.write(filename, str('%s.pdf' % book.slug))
394 if 'odt' in formats and book.odt_file:
395 filename = book.odt_file.path
396 archive.write(filename, str('%s.odt' % book.slug))
397 if 'txt' in formats and book.txt_file:
398 filename = book.txt_file.path
399 archive.write(filename, str('%s.txt' % book.slug))
400 if 'mp3' in formats and book.mp3_file:
401 filename = book.mp3_file.path
402 archive.write(filename, str('%s.mp3' % book.slug))
403 if 'ogg' in formats and book.ogg_file:
404 filename = book.ogg_file.path
405 archive.write(filename, str('%s.ogg' % book.slug))
408 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
409 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
410 response['Content-Length'] = temp.tell()
413 response.write(temp.read())
418 def shelf_book_formats(request, shelf):
420 Returns a list of formats of books in shelf.
422 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
424 formats = {'pdf': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
426 for book in collect_books(models.Book.tagged.with_all(shelf)):
428 formats['pdf'] = True
430 formats['odt'] = True
432 formats['txt'] = True
434 formats['mp3'] = True
436 formats['ogg'] = True
438 return HttpResponse(LazyEncoder().encode(formats))
444 def new_set(request):
445 new_set_form = forms.NewSetForm(request.POST)
446 if new_set_form.is_valid():
447 new_set = new_set_form.save(request.user)
449 if request.is_ajax():
450 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully created</p>') % new_set)
452 return HttpResponseRedirect('/')
454 return HttpResponseRedirect('/')
460 def delete_shelf(request, slug):
461 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
464 if request.is_ajax():
465 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
467 return HttpResponseRedirect('/')
476 form = AuthenticationForm(data=request.POST, prefix='login')
478 auth.login(request, form.get_user())
479 response_data = {'success': True, 'errors': {}}
481 response_data = {'success': False, 'errors': form.errors}
482 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
487 def register(request):
488 registration_form = UserCreationForm(request.POST, prefix='registration')
489 if registration_form.is_valid():
490 user = registration_form.save()
491 user = auth.authenticate(
492 username=registration_form.cleaned_data['username'],
493 password=registration_form.cleaned_data['password1']
495 auth.login(request, user)
496 response_data = {'success': True, 'errors': {}}
498 response_data = {'success': False, 'errors': registration_form.errors}
499 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
503 def logout_then_redirect(request):
505 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
514 def import_book(request):
515 """docstring for import_book"""
516 book_import_form = forms.BookImportForm(request.POST, request.FILES)
517 if book_import_form.is_valid():
519 book_import_form.save()
521 info = sys.exc_info()
522 exception = pprint.pformat(info[1])
523 tb = '\n'.join(traceback.format_tb(info[2]))
524 _('Today is %(month)s, %(day)s.') % {'month': m, 'day': d}
525 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
526 return HttpResponse(_("Book imported successfully"))
528 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
533 """ Provides server time for jquery.countdown,
534 in a format suitable for Date.parse()
536 from datetime import datetime
537 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))