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 operator import itemgetter
14 from django.conf import settings
15 from django.template import RequestContext
16 from django.shortcuts import render_to_response, get_object_or_404
17 from django.http import HttpResponse, HttpResponseRedirect, Http404
18 from django.core.urlresolvers import reverse
19 from django.db.models import Q
20 from django.contrib.auth.decorators import login_required, user_passes_test
21 from django.utils.datastructures import SortedDict
22 from django.views.decorators.http import require_POST
23 from django.contrib import auth
24 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
25 from django.utils import simplejson
26 from django.utils.functional import Promise
27 from django.utils.encoding import force_unicode
28 from django.utils.http import urlquote_plus
29 from django.views.decorators import cache
30 from django.utils.translation import ugettext as _
31 from django.views.generic.list_detail import object_list
33 from catalogue import models
34 from catalogue import forms
35 from catalogue.utils import split_tags
36 from newtagging import views as newtagging_views
39 staff_required = user_passes_test(lambda user: user.is_staff)
42 class LazyEncoder(simplejson.JSONEncoder):
43 def default(self, obj):
44 if isinstance(obj, Promise):
45 return force_unicode(obj)
48 # shortcut for JSON reponses
49 class JSONResponse(HttpResponse):
50 def __init__(self, data={}, callback=None, **kwargs):
52 kwargs.pop('mimetype', None)
53 data = simplejson.dumps(data)
55 data = callback + "(" + data + ");"
56 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
59 def main_page(request):
60 if request.user.is_authenticated():
61 shelves = models.Tag.objects.filter(category='set', user=request.user)
62 new_set_form = forms.NewSetForm()
64 tags = models.Tag.objects.exclude(category__in=('set', 'book'))
66 tag.count = tag.get_count()
67 categories = split_tags(tags)
68 fragment_tags = categories.get('theme', [])
70 form = forms.SearchForm()
71 return render_to_response('catalogue/main_page.html', locals(),
72 context_instance=RequestContext(request))
75 def book_list(request):
76 form = forms.SearchForm()
79 for book in models.Book.objects.all().order_by('parent_number'):
80 books_by_parent.setdefault(book.parent, []).append(book)
83 books_by_author = SortedDict()
84 books_nav = SortedDict()
85 for tag in models.Tag.objects.filter(category='author'):
86 books_by_author[tag] = []
87 if books_nav.has_key(tag.sort_key[0]):
88 books_nav[tag.sort_key[0]].append(tag)
90 books_nav[tag.sort_key[0]] = [tag]
92 for book in books_by_parent[None]:
93 authors = list(book.tags.filter(category='author'))
95 for author in authors:
96 books_by_author[author].append(book)
100 return render_to_response('catalogue/book_list.html', locals(),
101 context_instance=RequestContext(request))
104 def differentiate_tags(request, tags, ambiguous_slugs):
105 beginning = '/'.join(tag.url_chunk for tag in tags)
106 unparsed = '/'.join(ambiguous_slugs[1:])
108 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
110 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
113 return render_to_response('catalogue/differentiate_tags.html',
114 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
115 context_instance=RequestContext(request))
118 def tagged_object_list(request, tags=''):
120 tags = models.Tag.get_tag_list(tags)
121 except models.Tag.DoesNotExist:
123 except models.Tag.MultipleObjectsReturned, e:
124 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
127 if len(tags) > settings.MAX_TAG_LIST:
129 except AttributeError:
132 if len([tag for tag in tags if tag.category == 'book']):
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
140 objects = only_author = pd_counter = None
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)
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)
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]
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)
166 # get relevant books and their tags
167 objects = models.Book.tagged.with_all(tags)
169 # eliminate descendants
170 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
171 descendants_keys = [book.pk for book in models.Book.tagged.with_any(l_tags)]
173 objects = objects.exclude(pk__in=descendants_keys)
175 # get related tags from `tag_counter` and `theme_counter`
177 tags_pks = [tag.pk for tag in tags]
179 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
180 if tag_pk in tags_pks:
182 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
183 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
184 related_tags = [tag for tag in related_tags if tag not in tags]
185 for tag in related_tags:
186 tag.count = related_counts[tag.pk]
188 categories = split_tags(related_tags)
192 only_author = len(tags) == 1 and tags[0].category == 'author'
193 pd_counter = only_author and tags[0].goes_to_pd()
194 objects = models.Book.objects.none()
199 template_name='catalogue/tagged_object_list.html',
201 'categories': categories,
202 'only_shelf': only_shelf,
203 'only_author': only_author,
204 'pd_counter': pd_counter,
205 'only_my_shelf': only_my_shelf,
206 'formats_form': forms.DownloadFormatsForm(),
213 def book_fragments(request, book_slug, theme_slug):
214 book = get_object_or_404(models.Book, slug=book_slug)
215 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
216 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
217 fragments = models.Fragment.tagged.with_all([book_tag, theme])
219 form = forms.SearchForm()
220 return render_to_response('catalogue/book_fragments.html', locals(),
221 context_instance=RequestContext(request))
224 def book_detail(request, slug):
226 book = models.Book.objects.get(slug=slug)
227 except models.Book.DoesNotExist:
228 return book_stub_detail(request, slug)
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')
238 parents.append(_book.parent)
240 parents = reversed(parents)
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]
247 extra_info = book.get_extra_info_value()
249 form = forms.SearchForm()
250 return render_to_response('catalogue/book_detail.html', locals(),
251 context_instance=RequestContext(request))
254 def book_stub_detail(request, slug):
255 book = get_object_or_404(models.BookStub, slug=slug)
257 form = forms.SearchForm()
259 return render_to_response('catalogue/book_stub_detail.html', locals(),
260 context_instance=RequestContext(request))
263 def book_text(request, slug):
264 book = get_object_or_404(models.Book, slug=slug)
265 if not book.has_html_file():
268 for fragment in book.fragments.all():
269 for theme in fragment.tags.filter(category='theme'):
270 book_themes.setdefault(theme, []).append(fragment)
272 book_themes = book_themes.items()
273 book_themes.sort(key=lambda s: s[0].sort_key)
274 return render_to_response('catalogue/book_text.html', locals(),
275 context_instance=RequestContext(request))
282 def _no_diacritics_regexp(query):
283 """ returns a regexp for searching for a query without diacritics
285 should be locale-aware """
287 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źżŹŻ',
288 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
292 return u"(%s)" % '|'.join(names[l])
293 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
295 def unicode_re_escape(query):
296 """ Unicode-friendly version of re.escape """
297 return re.sub('(?u)(\W)', r'\\\1', query)
299 def _word_starts_with(name, prefix):
300 """returns a Q object getting models having `name` contain a word
301 starting with `prefix`
303 We define word characters as alphanumeric and underscore, like in JS.
305 Works for MySQL, PostgreSQL, Oracle.
306 For SQLite, _sqlite* version is substituted for this.
310 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
311 # can't use [[:<:]] (word start),
312 # but we want both `xy` and `(xy` to catch `(xyz)`
313 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
318 def _sqlite_word_starts_with(name, prefix):
319 """ version of _word_starts_with for SQLite
321 SQLite in Django uses Python re module
324 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
325 kwargs['%s__iregex' % name] = ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
329 if settings.DATABASE_ENGINE == 'sqlite3':
330 _word_starts_with = _sqlite_word_starts_with
333 def _tags_starting_with(prefix, user=None):
334 prefix = prefix.lower()
335 book_stubs = models.BookStub.objects.filter(_word_starts_with('title', prefix))
336 books = models.Book.objects.filter(_word_starts_with('title', prefix))
337 book_stubs = filter(lambda x: x not in books, book_stubs)
338 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
339 if user and user.is_authenticated():
340 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
342 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
343 return list(books) + list(tags) + list(book_stubs)
346 def _get_result_link(match, tag_list):
347 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
348 return match.get_absolute_url()
350 return reverse('catalogue.views.tagged_object_list',
351 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
354 def _get_result_type(match):
355 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
358 type = match.category
363 def find_best_matches(query, user=None):
364 """ Finds a Book, Tag or Bookstub best matching a query.
367 - zero elements when nothing is found,
368 - one element when a best result is found,
369 - more then one element on multiple exact matches
371 Raises a ValueError on too short a query.
374 query = query.lower()
376 raise ValueError("query must have at least two characters")
378 result = tuple(_tags_starting_with(query, user))
379 exact_matches = tuple(res for res in result if res.name.lower() == query)
387 tags = request.GET.get('tags', '')
388 prefix = request.GET.get('q', '')
391 tag_list = models.Tag.get_tag_list(tags)
396 result = find_best_matches(prefix, request.user)
398 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
399 context_instance=RequestContext(request))
402 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
403 elif len(result) > 1:
404 return render_to_response('catalogue/search_multiple_hits.html',
405 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
406 context_instance=RequestContext(request))
408 return render_to_response('catalogue/search_no_hits.html', {'tags':tag_list, 'prefix':prefix},
409 context_instance=RequestContext(request))
412 def tags_starting_with(request):
413 prefix = request.GET.get('q', '')
414 # Prefix must have at least 2 characters
416 return HttpResponse('')
419 for tag in _tags_starting_with(prefix, request.user):
420 if not tag.name in tags_list:
421 result += "\n" + tag.name
422 tags_list.append(tag.name)
423 return HttpResponse(result)
425 def json_tags_starting_with(request, callback=None):
427 prefix = request.GET.get('q', '')
428 callback = request.GET.get('callback', '')
429 # Prefix must have at least 2 characters
431 return HttpResponse('')
434 for tag in _tags_starting_with(prefix, request.user):
435 if not tag.name in tags_list:
436 result += "\n" + tag.name
437 tags_list.append(tag.name)
438 dict_result = {"matches": tags_list}
439 return JSONResponse(dict_result, callback)
441 # ====================
442 # = Shelf management =
443 # ====================
446 def user_shelves(request):
447 shelves = models.Tag.objects.filter(category='set', user=request.user)
448 new_set_form = forms.NewSetForm()
449 return render_to_response('catalogue/user_shelves.html', locals(),
450 context_instance=RequestContext(request))
453 def book_sets(request, slug):
454 book = get_object_or_404(models.Book, slug=slug)
455 user_sets = models.Tag.objects.filter(category='set', user=request.user)
456 book_sets = book.tags.filter(category='set', user=request.user)
458 if not request.user.is_authenticated():
459 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
461 if request.method == 'POST':
462 form = forms.ObjectSetsForm(book, request.user, request.POST)
464 old_shelves = list(book.tags.filter(category='set'))
465 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
467 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
468 shelf.book_count = None
471 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
472 shelf.book_count = None
475 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
476 if request.is_ajax():
477 return HttpResponse(_('<p>Shelves were sucessfully saved.</p>'))
479 return HttpResponseRedirect('/')
481 form = forms.ObjectSetsForm(book, request.user)
482 new_set_form = forms.NewSetForm()
484 return render_to_response('catalogue/book_sets.html', locals(),
485 context_instance=RequestContext(request))
491 def remove_from_shelf(request, shelf, book):
492 book = get_object_or_404(models.Book, slug=book)
493 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
495 if shelf in book.tags:
496 models.Tag.objects.remove_tag(book, shelf)
498 shelf.book_count = None
501 return HttpResponse(_('Book was successfully removed from the shelf'))
503 return HttpResponse(_('This book is not on the shelf'))
506 def collect_books(books):
508 Returns all real books in collection.
512 if len(book.children.all()) == 0:
515 result += collect_books(book.children.all())
520 def download_shelf(request, slug):
522 Create a ZIP archive on disk and transmit it in chunks of 8KB,
523 without loading the whole file into memory. A similar approach can
524 be used for large dynamic PDF files.
526 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
529 form = forms.DownloadFormatsForm(request.GET)
531 formats = form.cleaned_data['formats']
532 if len(formats) == 0:
533 formats = ['pdf', 'epub', 'odt', 'txt', 'mp3', 'ogg']
535 # Create a ZIP archive
536 temp = tempfile.TemporaryFile()
537 archive = zipfile.ZipFile(temp, 'w')
540 for book in collect_books(models.Book.tagged.with_all(shelf)):
541 if 'pdf' in formats and book.pdf_file:
542 filename = book.pdf_file.path
543 archive.write(filename, str('%s.pdf' % book.slug))
544 if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
545 filename = book.root_ancestor.epub_file.path
546 archive.write(filename, str('%s.epub' % book.root_ancestor.slug))
547 already.add(book.root_ancestor)
548 if 'odt' in formats and book.odt_file:
549 filename = book.odt_file.path
550 archive.write(filename, str('%s.odt' % book.slug))
551 if 'txt' in formats and book.txt_file:
552 filename = book.txt_file.path
553 archive.write(filename, str('%s.txt' % book.slug))
554 if 'mp3' in formats and book.mp3_file:
555 filename = book.mp3_file.path
556 archive.write(filename, str('%s.mp3' % book.slug))
557 if 'ogg' in formats and book.ogg_file:
558 filename = book.ogg_file.path
559 archive.write(filename, str('%s.ogg' % book.slug))
562 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
563 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
564 response['Content-Length'] = temp.tell()
567 response.write(temp.read())
572 def shelf_book_formats(request, shelf):
574 Returns a list of formats of books in shelf.
576 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
578 formats = {'pdf': False, 'epub': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
580 for book in collect_books(models.Book.tagged.with_all(shelf)):
582 formats['pdf'] = True
583 if book.root_ancestor.epub_file:
584 formats['epub'] = True
586 formats['odt'] = True
588 formats['txt'] = True
590 formats['mp3'] = True
592 formats['ogg'] = True
594 return HttpResponse(LazyEncoder().encode(formats))
600 def new_set(request):
601 new_set_form = forms.NewSetForm(request.POST)
602 if new_set_form.is_valid():
603 new_set = new_set_form.save(request.user)
605 if request.is_ajax():
606 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully created</p>') % new_set)
608 return HttpResponseRedirect('/')
610 return HttpResponseRedirect('/')
616 def delete_shelf(request, slug):
617 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
620 if request.is_ajax():
621 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
623 return HttpResponseRedirect('/')
632 form = AuthenticationForm(data=request.POST, prefix='login')
634 auth.login(request, form.get_user())
635 response_data = {'success': True, 'errors': {}}
637 response_data = {'success': False, 'errors': form.errors}
638 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
643 def register(request):
644 registration_form = UserCreationForm(request.POST, prefix='registration')
645 if registration_form.is_valid():
646 user = registration_form.save()
647 user = auth.authenticate(
648 username=registration_form.cleaned_data['username'],
649 password=registration_form.cleaned_data['password1']
651 auth.login(request, user)
652 response_data = {'success': True, 'errors': {}}
654 response_data = {'success': False, 'errors': registration_form.errors}
655 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
659 def logout_then_redirect(request):
661 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
670 def import_book(request):
671 """docstring for import_book"""
672 book_import_form = forms.BookImportForm(request.POST, request.FILES)
673 if book_import_form.is_valid():
675 book_import_form.save()
677 info = sys.exc_info()
678 exception = pprint.pformat(info[1])
679 tb = '\n'.join(traceback.format_tb(info[2]))
680 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
681 return HttpResponse(_("Book imported successfully"))
683 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
688 """ Provides server time for jquery.countdown,
689 in a format suitable for Date.parse()
691 from datetime import datetime
692 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))