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 books = models.Book.objects.all()
77 form = forms.SearchForm()
79 books_by_first_letter = SortedDict()
81 books_by_first_letter.setdefault(book.title[0], []).append(book)
83 return render_to_response('catalogue/book_list.html', locals(),
84 context_instance=RequestContext(request))
87 def differentiate_tags(request, tags, ambiguous_slugs):
88 beginning = '/'.join(tag.url_chunk for tag in tags)
89 unparsed = '/'.join(ambiguous_slugs[1:])
91 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
93 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
96 return render_to_response('catalogue/differentiate_tags.html',
97 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
98 context_instance=RequestContext(request))
101 def tagged_object_list(request, tags=''):
103 tags = models.Tag.get_tag_list(tags)
104 except models.Tag.DoesNotExist:
106 except models.Tag.MultipleObjectsReturned, e:
107 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
110 if len(tags) > settings.MAX_TAG_LIST:
112 except AttributeError:
115 if len([tag for tag in tags if tag.category == 'book']):
118 theme_is_set = [tag for tag in tags if tag.category == 'theme']
119 shelf_is_set = [tag for tag in tags if tag.category == 'set']
120 only_shelf = shelf_is_set and len(tags) == 1
121 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
123 objects = only_author = pd_counter = None
127 shelf_tags = [tag for tag in tags if tag.category == 'set']
128 fragment_tags = [tag for tag in tags if tag.category != 'set']
129 fragments = models.Fragment.tagged.with_all(fragment_tags)
132 books = models.Book.tagged.with_all(shelf_tags).order_by()
133 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
134 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
136 # newtagging goes crazy if we just try:
137 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
138 # extra={'where': ["catalogue_tag.category != 'book'"]})
139 fragment_keys = [fragment.pk for fragment in fragments]
141 related_tags = models.Fragment.tags.usage(counts=True,
142 filters={'pk__in': fragment_keys},
143 extra={'where': ["catalogue_tag.category != 'book'"]})
144 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
145 categories = split_tags(related_tags)
149 # get relevant books and their tags
150 objects = models.Book.tagged.with_all(tags).order_by()
152 # eliminate descendants
153 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
154 descendants_keys = [book.pk for book in models.Book.tagged.with_any(l_tags)]
156 objects = objects.exclude(pk__in=descendants_keys)
158 # get related tags from `tag_counter` and `theme_counter`
160 tags_pks = [tag.pk for tag in tags]
162 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
163 if tag_pk in tags_pks:
165 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
166 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
167 related_tags = [tag for tag in related_tags if tag not in tags]
168 for tag in related_tags:
169 tag.count = related_counts[tag.pk]
171 categories = split_tags(related_tags)
175 only_author = len(tags) == 1 and tags[0].category == 'author'
176 pd_counter = only_author and tags[0].goes_to_pd()
177 objects = models.Book.objects.none()
182 template_name='catalogue/tagged_object_list.html',
184 'categories': categories,
185 'only_shelf': only_shelf,
186 'only_author': only_author,
187 'pd_counter': pd_counter,
188 'only_my_shelf': only_my_shelf,
189 'formats_form': forms.DownloadFormatsForm(),
196 def book_fragments(request, book_slug, theme_slug):
197 book = get_object_or_404(models.Book, slug=book_slug)
198 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
199 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
200 fragments = models.Fragment.tagged.with_all([book_tag, theme])
202 form = forms.SearchForm()
203 return render_to_response('catalogue/book_fragments.html', locals(),
204 context_instance=RequestContext(request))
207 def book_detail(request, slug):
209 book = models.Book.objects.get(slug=slug)
210 except models.Book.DoesNotExist:
211 return book_stub_detail(request, slug)
213 book_tag = book.book_tag()
214 tags = list(book.tags.filter(~Q(category='set')))
215 categories = split_tags(tags)
216 book_children = book.children.all().order_by('parent_number')
218 theme_counter = book.theme_counter
219 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
220 for tag in book_themes:
221 tag.count = theme_counter[tag.pk]
223 extra_info = book.get_extra_info_value()
225 form = forms.SearchForm()
226 return render_to_response('catalogue/book_detail.html', locals(),
227 context_instance=RequestContext(request))
230 def book_stub_detail(request, slug):
231 book = get_object_or_404(models.BookStub, slug=slug)
233 form = forms.SearchForm()
235 return render_to_response('catalogue/book_stub_detail.html', locals(),
236 context_instance=RequestContext(request))
239 def book_text(request, slug):
240 book = get_object_or_404(models.Book, slug=slug)
242 for fragment in book.fragments.all():
243 for theme in fragment.tags.filter(category='theme'):
244 book_themes.setdefault(theme, []).append(fragment)
246 book_themes = book_themes.items()
247 book_themes.sort(key=lambda s: s[0].sort_key)
248 return render_to_response('catalogue/book_text.html', locals(),
249 context_instance=RequestContext(request))
256 def _no_diacritics_regexp(query):
257 """ returns a regexp for searching for a query without diacritics
259 should be locale-aware """
261 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źżŹŻ',
262 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
266 return u"(%s)" % '|'.join(names[l])
267 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
269 def unicode_re_escape(query):
270 """ Unicode-friendly version of re.escape """
271 return re.sub('(?u)(\W)', r'\\\1', query)
273 def _word_starts_with(name, prefix):
274 """returns a Q object getting models having `name` contain a word
275 starting with `prefix`
277 We define word characters as alphanumeric and underscore, like in JS.
279 Works for MySQL, PostgreSQL, Oracle.
280 For SQLite, _sqlite* version is substituted for this.
284 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
285 # can't use [[:<:]] (word start),
286 # but we want both `xy` and `(xy` to catch `(xyz)`
287 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
292 def _sqlite_word_starts_with(name, prefix):
293 """ version of _word_starts_with for SQLite
295 SQLite in Django uses Python re module
298 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
299 kwargs['%s__iregex' % name] = ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
303 if settings.DATABASE_ENGINE == 'sqlite3':
304 _word_starts_with = _sqlite_word_starts_with
307 def _tags_starting_with(prefix, user=None):
308 prefix = prefix.lower()
309 book_stubs = models.BookStub.objects.filter(_word_starts_with('title', prefix))
310 books = models.Book.objects.filter(_word_starts_with('title', prefix))
311 book_stubs = filter(lambda x: x not in books, book_stubs)
312 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
313 if user and user.is_authenticated():
314 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
316 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
317 return list(books) + list(tags) + list(book_stubs)
320 def _get_result_link(match, tag_list):
321 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
322 return match.get_absolute_url()
324 return reverse('catalogue.views.tagged_object_list',
325 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
328 def _get_result_type(match):
329 if isinstance(match, models.Book) or isinstance(match, models.BookStub):
332 type = match.category
337 def find_best_matches(query, user=None):
338 """ Finds a Book, Tag or Bookstub best matching a query.
341 - zero elements when nothing is found,
342 - one element when a best result is found,
343 - more then one element on multiple exact matches
345 Raises a ValueError on too short a query.
348 query = query.lower()
350 raise ValueError("query must have at least two characters")
352 result = tuple(_tags_starting_with(query, user))
353 exact_matches = tuple(res for res in result if res.name.lower() == query)
361 tags = request.GET.get('tags', '')
362 prefix = request.GET.get('q', '')
365 tag_list = models.Tag.get_tag_list(tags)
370 result = find_best_matches(prefix, request.user)
372 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
373 context_instance=RequestContext(request))
376 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
377 elif len(result) > 1:
378 return render_to_response('catalogue/search_multiple_hits.html',
379 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
380 context_instance=RequestContext(request))
382 return render_to_response('catalogue/search_no_hits.html', {'tags':tag_list, 'prefix':prefix},
383 context_instance=RequestContext(request))
386 def tags_starting_with(request):
387 prefix = request.GET.get('q', '')
388 # Prefix must have at least 2 characters
390 return HttpResponse('')
393 for tag in _tags_starting_with(prefix, request.user):
394 if not tag.name in tags_list:
395 result += "\n" + tag.name
396 tags_list.append(tag.name)
397 return HttpResponse(result)
399 def json_tags_starting_with(request, callback=None):
401 prefix = request.GET.get('q', '')
402 callback = request.GET.get('callback', '')
403 # Prefix must have at least 2 characters
405 return HttpResponse('')
408 for tag in _tags_starting_with(prefix, request.user):
409 if not tag.name in tags_list:
410 result += "\n" + tag.name
411 tags_list.append(tag.name)
412 dict_result = {"matches": tags_list}
413 return JSONResponse(dict_result, callback)
415 # ====================
416 # = Shelf management =
417 # ====================
420 def user_shelves(request):
421 shelves = models.Tag.objects.filter(category='set', user=request.user)
422 new_set_form = forms.NewSetForm()
423 return render_to_response('catalogue/user_shelves.html', locals(),
424 context_instance=RequestContext(request))
427 def book_sets(request, slug):
428 book = get_object_or_404(models.Book, slug=slug)
429 user_sets = models.Tag.objects.filter(category='set', user=request.user)
430 book_sets = book.tags.filter(category='set', user=request.user)
432 if not request.user.is_authenticated():
433 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
435 if request.method == 'POST':
436 form = forms.ObjectSetsForm(book, request.user, request.POST)
438 old_shelves = list(book.tags.filter(category='set'))
439 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
441 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
442 shelf.book_count = None
445 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
446 shelf.book_count = None
449 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
450 if request.is_ajax():
451 return HttpResponse(_('<p>Shelves were sucessfully saved.</p>'))
453 return HttpResponseRedirect('/')
455 form = forms.ObjectSetsForm(book, request.user)
456 new_set_form = forms.NewSetForm()
458 return render_to_response('catalogue/book_sets.html', locals(),
459 context_instance=RequestContext(request))
465 def remove_from_shelf(request, shelf, book):
466 book = get_object_or_404(models.Book, slug=book)
467 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
469 if shelf in book.tags:
470 models.Tag.objects.remove_tag(book, shelf)
472 shelf.book_count = None
475 return HttpResponse(_('Book was successfully removed from the shelf'))
477 return HttpResponse(_('This book is not on the shelf'))
480 def collect_books(books):
482 Returns all real books in collection.
486 if len(book.children.all()) == 0:
489 result += collect_books(book.children.all())
494 def download_shelf(request, slug):
496 Create a ZIP archive on disk and transmit it in chunks of 8KB,
497 without loading the whole file into memory. A similar approach can
498 be used for large dynamic PDF files.
500 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
503 form = forms.DownloadFormatsForm(request.GET)
505 formats = form.cleaned_data['formats']
506 if len(formats) == 0:
507 formats = ['pdf', 'epub', 'odt', 'txt', 'mp3', 'ogg']
509 # Create a ZIP archive
510 temp = tempfile.TemporaryFile()
511 archive = zipfile.ZipFile(temp, 'w')
513 for book in collect_books(models.Book.tagged.with_all(shelf)):
514 if 'pdf' in formats and book.pdf_file:
515 filename = book.pdf_file.path
516 archive.write(filename, str('%s.pdf' % book.slug))
517 if 'epub' in formats and book.epub_file:
518 filename = book.epub_file.path
519 archive.write(filename, str('%s.epub' % book.slug))
520 if 'odt' in formats and book.odt_file:
521 filename = book.odt_file.path
522 archive.write(filename, str('%s.odt' % book.slug))
523 if 'txt' in formats and book.txt_file:
524 filename = book.txt_file.path
525 archive.write(filename, str('%s.txt' % book.slug))
526 if 'mp3' in formats and book.mp3_file:
527 filename = book.mp3_file.path
528 archive.write(filename, str('%s.mp3' % book.slug))
529 if 'ogg' in formats and book.ogg_file:
530 filename = book.ogg_file.path
531 archive.write(filename, str('%s.ogg' % book.slug))
534 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
535 response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
536 response['Content-Length'] = temp.tell()
539 response.write(temp.read())
544 def shelf_book_formats(request, shelf):
546 Returns a list of formats of books in shelf.
548 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
550 formats = {'pdf': False, 'epub': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
552 for book in collect_books(models.Book.tagged.with_all(shelf)):
554 formats['pdf'] = True
556 formats['epub'] = True
558 formats['odt'] = True
560 formats['txt'] = True
562 formats['mp3'] = True
564 formats['ogg'] = True
566 return HttpResponse(LazyEncoder().encode(formats))
572 def new_set(request):
573 new_set_form = forms.NewSetForm(request.POST)
574 if new_set_form.is_valid():
575 new_set = new_set_form.save(request.user)
577 if request.is_ajax():
578 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully created</p>') % new_set)
580 return HttpResponseRedirect('/')
582 return HttpResponseRedirect('/')
588 def delete_shelf(request, slug):
589 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
592 if request.is_ajax():
593 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
595 return HttpResponseRedirect('/')
604 form = AuthenticationForm(data=request.POST, prefix='login')
606 auth.login(request, form.get_user())
607 response_data = {'success': True, 'errors': {}}
609 response_data = {'success': False, 'errors': form.errors}
610 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
615 def register(request):
616 registration_form = UserCreationForm(request.POST, prefix='registration')
617 if registration_form.is_valid():
618 user = registration_form.save()
619 user = auth.authenticate(
620 username=registration_form.cleaned_data['username'],
621 password=registration_form.cleaned_data['password1']
623 auth.login(request, user)
624 response_data = {'success': True, 'errors': {}}
626 response_data = {'success': False, 'errors': registration_form.errors}
627 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
631 def logout_then_redirect(request):
633 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
642 def import_book(request):
643 """docstring for import_book"""
644 book_import_form = forms.BookImportForm(request.POST, request.FILES)
645 if book_import_form.is_valid():
647 book_import_form.save()
649 info = sys.exc_info()
650 exception = pprint.pformat(info[1])
651 tb = '\n'.join(traceback.format_tb(info[2]))
652 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
653 return HttpResponse(_("Book imported successfully"))
655 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
660 """ Provides server time for jquery.countdown,
661 in a format suitable for Date.parse()
663 from datetime import datetime
664 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))