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.
5 from collections import OrderedDict
9 from django.conf import settings
10 from django.template import RequestContext
11 from django.template.loader import render_to_string
12 from django.shortcuts import render_to_response, get_object_or_404, render, redirect
13 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
14 from django.core.urlresolvers import reverse
15 from django.db.models import Q
16 from django.contrib.auth.decorators import login_required, user_passes_test
17 from django.utils.http import urlquote_plus
18 from django.utils import translation
19 from django.utils.translation import ugettext as _, ugettext_lazy
21 from ajaxable.utils import AjaxableFormView
22 from pdcounter.models import BookStub, Author
23 from pdcounter import views as pdcounter_views
24 from picture.models import Picture, PictureArea
25 from ssify import ssi_included, ssi_expect, SsiVariable as Var
26 from suggest.forms import PublishingSuggestForm
27 from catalogue import constants
28 from catalogue import forms
29 from catalogue.helpers import get_top_level_related_tags
30 from catalogue.models import Book, Collection, Tag, Fragment
31 from catalogue.utils import split_tags
33 staff_required = user_passes_test(lambda user: user.is_staff)
36 def catalogue(request):
37 return render(request, 'catalogue/catalogue.html', {
38 'books': Book.objects.filter(parent=None).order_by('sort_key_author', 'sort_key'),
39 'pictures': Picture.objects.order_by('sort_key_author', 'sort_key'),
40 'collections': Collection.objects.all(),
41 'active_menu_item': 'all_works',
45 def book_list(request, filter=None, get_filter=None, template_name='catalogue/book_list.html',
46 nav_template_name='catalogue/snippets/book_list_nav.html',
47 list_template_name='catalogue/snippets/book_list.html', context=None):
48 """ generates a listing of all books, optionally filtered with a test function """
51 books_by_author, orphans, books_by_parent = Book.book_list(filter)
52 books_nav = OrderedDict()
53 for tag in books_by_author:
54 if books_by_author[tag]:
55 books_nav.setdefault(tag.sort_key[0], []).append(tag)
56 # WTF: dlaczego nie include?
57 return render_to_response(template_name, {
58 'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
59 'rendered_book_list': render_to_string(list_template_name, {
60 'books_by_author': books_by_author,
62 'books_by_parent': books_by_parent,
64 }, context_instance=RequestContext(request))
67 def audiobook_list(request):
68 books = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct().order_by(
69 'sort_key_author', 'sort_key')
72 best = random.sample(books, 3)
76 daisy = Book.objects.filter(media__type='daisy').distinct().order_by('sort_key_author', 'sort_key')
78 return render(request, 'catalogue/audiobook_list.html', {
85 def daisy_list(request):
86 return book_list(request, Q(media__type='daisy'),
87 template_name='catalogue/daisy_list.html',
91 def collection(request, slug):
92 coll = get_object_or_404(Collection, slug=slug)
93 return render(request, 'catalogue/collection.html', {'collection': coll})
96 def differentiate_tags(request, tags, ambiguous_slugs):
97 beginning = '/'.join(tag.url_chunk for tag in tags)
98 unparsed = '/'.join(ambiguous_slugs[1:])
100 for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
102 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
105 return render_to_response(
106 'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
107 context_instance=RequestContext(request))
110 # TODO: Rewrite this hellish piece of code which tries to do everything
111 def tagged_object_list(request, tags='', list_type='books'):
113 # preliminary tests and conditions
114 gallery = list_type == 'gallery'
115 audiobooks = list_type == 'audiobooks'
117 tags = Tag.get_tag_list(tags)
118 except Tag.DoesNotExist:
119 # Perhaps the user is asking about an author in Public Domain
120 # counter (they are not represented in tags)
121 chunks = tags.split('/')
122 if len(chunks) == 2 and chunks[0] == 'autor':
123 return pdcounter_views.author_detail(request, chunks[1])
126 except Tag.MultipleObjectsReturned, e:
127 # Ask the user to disambiguate
128 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
129 except Tag.UrlDeprecationWarning, e:
130 return HttpResponsePermanentRedirect(
131 reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
134 if len(tags) > settings.MAX_TAG_LIST:
136 except AttributeError:
139 # beginning of digestion
140 theme_is_set = any(tag.category == 'theme' for tag in tags)
141 shelf_is_set = any(tag.category == 'set' for tag in tags)
142 only_shelf = shelf_is_set and len(tags) == 1
143 only_my_shelf = only_shelf and request.user == tags[0].user
144 tags_pks = [tag.pk for tag in tags]
146 if gallery and shelf_is_set:
151 # Only fragments (or pirctureareas) here.
152 shelf_tags = [tag for tag in tags if tag.category == 'set']
153 fragment_tags = [tag for tag in tags if tag.category != 'set']
155 fragments = PictureArea.tagged.with_all(fragment_tags)
157 fragments = Fragment.tagged.with_all(fragment_tags)
160 # TODO: Pictures on shelves not supported yet.
161 books = Book.tagged.with_all(shelf_tags).order_by()
162 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
164 categories = split_tags(
165 Tag.objects.usage_for_queryset(fragments, counts=True).exclude(pk__in=tags_pks),
171 # TODO: Pictures on shelves not supported yet.
173 objects = Picture.tagged.with_all(tags)
175 objects = Picture.objects.all()
176 areas = PictureArea.objects.filter(picture__in=objects)
177 categories = split_tags(
178 Tag.objects.usage_for_queryset(
179 objects, counts=True).exclude(pk__in=tags_pks),
180 Tag.objects.usage_for_queryset(
181 areas, counts=True).filter(
182 category__in=('theme', 'thing')).exclude(
187 all_books = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct()
189 all_books = Book.tagged.with_all(tags, all_books)
191 # there's never only the daisy audiobook
192 daisy = objects.filter(media__type='daisy').distinct().order_by('sort_key_author', 'sort_key')
193 related_book_tags = Tag.objects.usage_for_queryset(
194 objects, counts=True).exclude(
195 category='set').exclude(pk__in=tags_pks)
198 all_books = Book.tagged.with_all(tags)
200 all_books = Book.objects.filter(parent=None)
203 related_book_tags = Tag.objects.usage_for_queryset(
204 objects, counts=True).exclude(
205 category='set').exclude(pk__in=tags_pks)
208 objects = Book.tagged_top_level(tags)
211 related_book_tags = get_top_level_related_tags(tags)
213 fragments = Fragment.objects.filter(book__in=all_books)
215 categories = split_tags(
217 Tag.objects.usage_for_queryset(
218 fragments, counts=True).filter(
219 category='theme').exclude(pk__in=tags_pks),
221 objects = objects.order_by('sort_key_author', 'sort_key')
223 objects = list(objects)
225 best = random.sample(objects, 3)
229 if not gallery and not objects and len(tags) == 1:
231 if tag.category in ('theme', 'thing') and (
232 PictureArea.tagged.with_any([tag]).exists() or
233 Picture.tagged.with_any([tag]).exists()):
234 return redirect('tagged_object_list_gallery', raw_tags)
236 # this is becoming more and more hacky
237 if list_type == 'books' and not tags:
238 last_published = Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:20]
239 most_popular = Book.objects.exclude(cover_thumb='').order_by('-popularity__count')[:20]
241 last_published = None
244 return render_to_response(
245 'catalogue/tagged_object_list.html',
247 'object_list': objects,
248 'categories': categories,
249 'only_shelf': only_shelf,
250 'only_my_shelf': only_my_shelf,
251 'formats_form': forms.DownloadFormatsForm(),
254 'theme_is_set': theme_is_set,
256 'list_type': list_type,
258 'last_published': last_published,
259 'most_popular': most_popular,
260 'active_menu_item': 'theme' if theme_is_set else list_type,
262 context_instance=RequestContext(request))
265 def book_fragments(request, slug, theme_slug):
266 book = get_object_or_404(Book, slug=slug)
267 theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
268 fragments = Fragment.tagged.with_all([theme]).filter(
269 Q(book=book) | Q(book__ancestor=book))
271 return render_to_response('catalogue/book_fragments.html', {
274 'fragments': fragments,
275 }, context_instance=RequestContext(request))
278 def book_detail(request, slug):
280 book = Book.objects.get(slug=slug)
281 except Book.DoesNotExist:
282 return pdcounter_views.book_stub_detail(request, slug)
284 return render_to_response('catalogue/book_detail.html', {
286 'tags': book.tags.exclude(category__in=('set', 'theme')),
287 'book_children': book.children.all().order_by('parent_number', 'sort_key'),
288 }, context_instance=RequestContext(request))
291 def get_audiobooks(book):
293 for m in book.media.filter(type='ogg').order_by().iterator():
294 ogg_files[m.name] = m
299 for mp3 in book.media.filter(type='mp3').iterator():
300 # ogg files are always from the same project
301 meta = mp3.extra_info
302 project = meta.get('project')
305 project = u'CzytamySłuchając'
307 projects.add((project, meta.get('funded_by', '')))
311 ogg = ogg_files.get(mp3.name)
316 audiobooks.append(media)
318 projects = sorted(projects)
319 return audiobooks, projects, have_oggs
322 # używane tylko do audiobook_tree, które jest używane tylko w snippets/audiobook_list.html, które nie jest używane
323 def player(request, slug):
324 book = get_object_or_404(Book, slug=slug)
325 if not book.has_media('mp3'):
328 audiobooks, projects, have_oggs = get_audiobooks(book)
330 # extra_info = book.extra_info
332 return render_to_response('catalogue/player.html', {
335 'audiobooks': audiobooks,
336 'projects': projects,
337 }, context_instance=RequestContext(request))
340 def book_text(request, slug):
341 book = get_object_or_404(Book, slug=slug)
343 if not book.has_html_file():
345 return render_to_response('catalogue/book_text.html', {'book': book,}, context_instance=RequestContext(request))
352 def _no_diacritics_regexp(query):
353 """ returns a regexp for searching for a query without diacritics
355 should be locale-aware """
357 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śŚ',
359 u'ą': u'ąĄ', u'ć': u'ćĆ', u'ę': u'ęĘ', u'ł': u'łŁ', u'ń': u'ńŃ', u'ó': u'óÓ', u'ś': u'śŚ', u'ź': u'źŹ',
365 return u"(%s)" % '|'.join(names[l])
367 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
370 def unicode_re_escape(query):
371 """ Unicode-friendly version of re.escape """
372 return re.sub(r'(?u)(\W)', r'\\\1', query)
375 def _word_starts_with(name, prefix):
376 """returns a Q object getting models having `name` contain a word
377 starting with `prefix`
379 We define word characters as alphanumeric and underscore, like in JS.
381 Works for MySQL, PostgreSQL, Oracle.
382 For SQLite, _sqlite* version is substituted for this.
386 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
387 # can't use [[:<:]] (word start),
388 # but we want both `xy` and `(xy` to catch `(xyz)`
389 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
394 def _word_starts_with_regexp(prefix):
395 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
396 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
399 def _sqlite_word_starts_with(name, prefix):
400 """ version of _word_starts_with for SQLite
402 SQLite in Django uses Python re module
404 kwargs = {'%s__iregex' % name: _word_starts_with_regexp(prefix)}
408 if hasattr(settings, 'DATABASES'):
409 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
410 _word_starts_with = _sqlite_word_starts_with
411 elif settings.DATABASE_ENGINE == 'sqlite3':
412 _word_starts_with = _sqlite_word_starts_with
416 def __init__(self, name, view):
419 self.lower = name.lower()
420 self.category = 'application'
423 return reverse(*self._view)
426 App(u'Leśmianator', (u'lesmianator', )),
430 def _tags_starting_with(prefix, user=None):
431 prefix = prefix.lower()
433 book_stubs = BookStub.objects.filter(_word_starts_with('title', prefix))
434 authors = Author.objects.filter(_word_starts_with('name', prefix))
436 books = Book.objects.filter(_word_starts_with('title', prefix))
437 tags = Tag.objects.filter(_word_starts_with('name', prefix))
438 if user and user.is_authenticated():
439 tags = tags.filter(~Q(category='set') | Q(user=user))
441 tags = tags.exclude(category='set')
443 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
444 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + \
448 def _get_result_link(match, tag_list):
449 if isinstance(match, Tag):
450 return reverse('catalogue.views.tagged_object_list',
451 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])})
452 elif isinstance(match, App):
455 return match.get_absolute_url()
458 def _get_result_type(match):
459 if isinstance(match, Book) or isinstance(match, BookStub):
462 match_type = match.category
466 def books_starting_with(prefix):
467 prefix = prefix.lower()
468 return Book.objects.filter(_word_starts_with('title', prefix))
471 def find_best_matches(query, user=None):
472 """ Finds a Book, Tag, BookStub or Author best matching a query.
475 - zero elements when nothing is found,
476 - one element when a best result is found,
477 - more then one element on multiple exact matches
479 Raises a ValueError on too short a query.
482 query = query.lower()
484 raise ValueError("query must have at least two characters")
486 result = tuple(_tags_starting_with(query, user))
487 # remove pdcounter stuff
488 book_titles = set(match.pretty_title().lower() for match in result
489 if isinstance(match, Book))
490 authors = set(match.name.lower() for match in result
491 if isinstance(match, Tag) and match.category == 'author')
492 result = tuple(res for res in result if not (
493 (isinstance(res, BookStub) and res.pretty_title().lower() in book_titles) or
494 (isinstance(res, Author) and res.name.lower() in authors)
497 exact_matches = tuple(res for res in result if res.name.lower() == query)
501 return tuple(result)[:1]
505 tags = request.GET.get('tags', '')
506 prefix = request.GET.get('q', '')
509 tag_list = Tag.get_tag_list(tags)
510 except (Tag.DoesNotExist, Tag.MultipleObjectsReturned, Tag.UrlDeprecationWarning):
514 result = find_best_matches(prefix, request.user)
516 return render_to_response(
517 'catalogue/search_too_short.html', {'tags': tag_list, 'prefix': prefix},
518 context_instance=RequestContext(request))
521 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
522 elif len(result) > 1:
523 return render_to_response(
524 'catalogue/search_multiple_hits.html',
526 'tags': tag_list, 'prefix': prefix,
527 'results': ((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)
529 context_instance=RequestContext(request))
531 form = PublishingSuggestForm(initial={"books": prefix + ", "})
532 return render_to_response(
533 'catalogue/search_no_hits.html',
534 {'tags': tag_list, 'prefix': prefix, "pubsuggest_form": form},
535 context_instance=RequestContext(request))
538 def tags_starting_with(request):
539 prefix = request.GET.get('q', '')
540 # Prefix must have at least 2 characters
542 return HttpResponse('')
545 for tag in _tags_starting_with(prefix, request.user):
546 if tag.name not in tags_list:
547 result += "\n" + tag.name
548 tags_list.append(tag.name)
549 return HttpResponse(result)
552 def json_tags_starting_with(request, callback=None):
554 prefix = request.GET.get('q', '')
555 callback = request.GET.get('callback', '')
556 # Prefix must have at least 2 characters
558 return HttpResponse('')
560 for tag in _tags_starting_with(prefix, request.user):
561 if tag.name not in tags_list:
562 tags_list.append(tag.name)
563 if request.GET.get('mozhint', ''):
564 result = [prefix, tags_list]
566 result = {"matches": tags_list}
567 response = JsonResponse(result, safe=False)
569 response.content = callback + "(" + response.content + ");"
578 def import_book(request):
579 """docstring for import_book"""
580 book_import_form = forms.BookImportForm(request.POST, request.FILES)
581 if book_import_form.is_valid():
583 book_import_form.save()
588 info = sys.exc_info()
589 exception = pprint.pformat(info[1])
590 tb = '\n'.join(traceback.format_tb(info[2]))
592 _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
593 mimetype='text/plain')
594 return HttpResponse(_("Book imported successfully"))
596 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
601 def book_info(request, book_id, lang='pl'):
602 book = get_object_or_404(Book, id=book_id)
603 # set language by hand
604 translation.activate(lang)
605 return render_to_response('catalogue/book_info.html', {'book': book}, context_instance=RequestContext(request))
608 def tag_info(request, tag_id):
609 tag = get_object_or_404(Tag, id=tag_id)
610 return HttpResponse(tag.description)
613 def download_zip(request, format, slug=None):
614 if format in Book.ebook_formats:
615 url = Book.zip_format(format)
616 elif format in ('mp3', 'ogg') and slug is not None:
617 book = get_object_or_404(Book, slug=slug)
618 url = book.zip_audiobooks(format)
620 raise Http404('No format specified for zip package')
621 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
624 class CustomPDFFormView(AjaxableFormView):
625 form_class = forms.CustomPDFForm
626 title = ugettext_lazy('Download custom PDF')
627 submit = ugettext_lazy('Download')
630 def __call__(self, *args, **kwargs):
631 if settings.NO_CUSTOM_PDF:
632 raise Http404('Custom PDF is disabled')
633 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
635 def form_args(self, request, obj):
636 """Override to parse view args and give additional args to the form."""
639 def get_object(self, request, slug, *args, **kwargs):
640 return get_object_or_404(Book, slug=slug)
642 def context_description(self, request, obj):
643 return obj.pretty_title()
652 def book_mini(request, pk, with_link=True):
653 book = get_object_or_404(Book, pk=pk)
654 author_str = ", ".join(tag.name for tag in book.tags.filter(category='author'))
655 return render(request, 'catalogue/book_mini_box.html', {
657 'author_str': author_str,
658 'with_link': with_link,
659 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
663 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
664 ('ssify.get_csrf_token',),
665 ('social_tags.likes_book', (ipk,)),
666 ('social_tags.book_shelf_tags', (ipk,)),
667 ))(ssi_expect(pk, int)))
668 def book_short(request, pk):
669 book = get_object_or_404(Book, pk=pk)
670 stage_note, stage_note_url = book.stage_note()
671 audiobooks, projects, have_oggs = get_audiobooks(book)
673 return render(request, 'catalogue/book_short.html', {
675 'has_audio': book.has_media('mp3'),
676 'main_link': book.get_absolute_url(),
677 'parents': book.parents(),
678 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
679 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
680 'stage_note': stage_note,
681 'stage_note_url': stage_note_url,
682 'audiobooks': audiobooks,
683 'have_oggs': have_oggs,
688 get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
690 ('social_tags.choose_cite', [ipk]),
691 ('catalogue_tags.choose_fragment', [ipk], {
692 'unless': Var('social_tags.choose_cite', [ipk])}),
693 ))(ssi_expect(pk, int)))
694 def book_wide(request, pk):
695 book = get_object_or_404(Book, pk=pk)
696 stage_note, stage_note_url = book.stage_note()
697 extra_info = book.extra_info
698 audiobooks, projects, have_oggs = get_audiobooks(book)
700 return render(request, 'catalogue/book_wide.html', {
702 'has_audio': book.has_media('mp3'),
703 'parents': book.parents(),
704 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
705 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
706 'stage_note': stage_note,
707 'stage_note_url': stage_note_url,
709 'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
710 'extra_info': extra_info,
711 'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
712 'audiobooks': audiobooks,
713 'have_oggs': have_oggs,
718 def fragment_short(request, pk):
719 fragment = get_object_or_404(Fragment, pk=pk)
720 return render(request, 'catalogue/fragment_short.html', {'fragment': fragment})
724 def fragment_promo(request, pk):
725 fragment = get_object_or_404(Fragment, pk=pk)
726 return render(request, 'catalogue/fragment_promo.html', {'fragment': fragment})
730 def tag_box(request, pk):
731 tag = get_object_or_404(Tag, pk=pk)
732 assert tag.category != 'set'
734 return render(request, 'catalogue/tag_box.html', {
740 def collection_box(request, pk):
741 obj = get_object_or_404(Collection, pk=pk)
743 return render(request, 'catalogue/collection_box.html', {
748 def tag_catalogue(request, category):
749 if category == 'theme':
750 tags = Tag.objects.usage_for_model(
751 Fragment, counts=True).filter(category='theme')
753 tags = list(get_top_level_related_tags((), categories=(category,)))
755 described_tags = [tag for tag in tags if tag.description]
757 if len(described_tags) > 4:
758 best = random.sample(described_tags, 4)
760 best = described_tags
762 return render(request, 'catalogue/tag_catalogue.html', {
765 'title': constants.CATEGORIES_NAME_PLURAL[category],
766 'whole_category': constants.WHOLE_CATEGORY[category],
767 'active_menu_item': 'theme' if category == 'theme' else None,
771 def collections(request):
772 objects = Collection.objects.all()
775 best = random.sample(objects, 3)
779 return render(request, 'catalogue/collections.html', {