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 import models as pdcounter_models
23 from pdcounter import views as pdcounter_views
24 from picture.models import Picture, PictureArea
25 from picture.views import picture_list_thumb
26 from ssify import ssi_included, ssi_expect, SsiVariable as V
27 from suggest.forms import PublishingSuggestForm
28 from catalogue import constants
29 from catalogue import forms
30 from catalogue.helpers import get_top_level_related_tags
31 from catalogue import models
32 from catalogue.utils import split_tags
33 from catalogue.templatetags.catalogue_tags import tag_list, collection_list
35 staff_required = user_passes_test(lambda user: user.is_staff)
38 def catalogue(request, as_json=False):
39 books = models.Book.objects.filter(parent=None)
40 pictures = Picture.objects.all()
41 collections = models.Collection.objects.all()
42 return render(request, 'catalogue/catalogue.html', locals())
45 def book_list(request, filter=None, get_filter=None,
46 template_name='catalogue/book_list.html',
47 nav_template_name='catalogue/snippets/book_list_nav.html',
48 list_template_name='catalogue/snippets/book_list.html',
51 """ generates a listing of all books, optionally filtered with a test function """
54 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
55 books_nav = OrderedDict()
56 for tag in books_by_author:
57 if books_by_author[tag]:
58 books_nav.setdefault(tag.sort_key[0], []).append(tag)
59 rendered_nav = render_to_string(nav_template_name, locals())
60 rendered_book_list = render_to_string(list_template_name, locals())
61 return render_to_response(template_name, locals(),
62 context_instance=RequestContext(request))
65 def audiobook_list(request):
66 books = models.Book.objects.filter(Q(media__type='mp3') | Q(media__type='ogg')).distinct()
69 best = random.sample(books, 3)
73 daisy = models.Book.objects.filter(media__type='daisy').distinct()
75 return render(request, 'catalogue/audiobook_list.html', {
82 def daisy_list(request):
83 return book_list(request, Q(media__type='daisy'),
84 template_name='catalogue/daisy_list.html',
88 def collection(request, slug):
89 coll = get_object_or_404(models.Collection, slug=slug)
90 return render(request, 'catalogue/collection.html',
94 def differentiate_tags(request, tags, ambiguous_slugs):
95 beginning = '/'.join(tag.url_chunk for tag in tags)
96 unparsed = '/'.join(ambiguous_slugs[1:])
98 for tag in models.Tag.objects.filter(slug=ambiguous_slugs[0]):
100 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
103 return render_to_response('catalogue/differentiate_tags.html',
104 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
105 context_instance=RequestContext(request))
108 # TODO: Rewrite this hellish piece of code which tries to do everything
109 def tagged_object_list(request, tags='', gallery=False):
111 # preliminary tests and conditions
113 tags = models.Tag.get_tag_list(tags)
114 except models.Tag.DoesNotExist:
115 # Perhaps the user is asking about an author in Public Domain
116 # counter (they are not represented in tags)
117 chunks = tags.split('/')
118 if len(chunks) == 2 and chunks[0] == 'autor':
119 return pdcounter_views.author_detail(request, chunks[1])
122 except models.Tag.MultipleObjectsReturned, e:
123 # Ask the user to disambiguate
124 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
125 except models.Tag.UrlDeprecationWarning, e:
126 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
129 if len(tags) > settings.MAX_TAG_LIST:
131 except AttributeError:
134 # beginning of digestion
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
139 tags_pks = [tag.pk for tag in tags]
144 # Only fragments (or pirctureareas) here.
145 shelf_tags = [tag for tag in tags if tag.category == 'set']
146 fragment_tags = [tag for tag in tags if tag.category != 'set']
148 fragments = PictureArea.tagged.with_all(fragment_tags)
150 fragments = models.Fragment.tagged.with_all(fragment_tags)
154 # TODO: Pictures on shelves not supported yet.
157 books = models.Book.tagged.with_all(shelf_tags).order_by()
158 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
160 categories = split_tags(
161 models.Tag.objects.usage_for_queryset(fragments, counts=True
162 ).exclude(pk__in=tags_pks),
169 # TODO: Pictures on shelves not supported yet.
173 objects = Picture.tagged.with_all(tags).order_by(
174 'sort_key_author', 'title')
176 objects = Picture.objects.all().order_by(
177 'sort_key_author', 'title')
178 areas = PictureArea.objects.filter(picture__in=objects)
179 categories = split_tags(
180 models.Tag.objects.usage_for_queryset(
181 objects, counts=True).exclude(pk__in=tags_pks),
182 models.Tag.objects.usage_for_queryset(
183 areas, counts=True).filter(
184 category__in=('theme', 'thing')).exclude(
189 all_books = models.Book.tagged.with_all(tags)
191 all_books = models.Book.objects.filter(parent=None)
193 objects = all_books.order_by('sort_key_author', 'title')
194 related_book_tags = models.Tag.objects.usage_for_queryset(
195 objects, counts=True).exclude(
196 category='set').exclude(pk__in=tags_pks)
199 objects = models.Book.tagged_top_level(tags).order_by(
200 'sort_key_author', 'title')
202 objects = all_books.order_by('sort_key_author', 'title')
203 related_book_tags = get_top_level_related_tags(tags)
205 fragments = models.Fragment.objects.filter(book__in=all_books)
207 categories = split_tags(
209 models.Tag.objects.usage_for_queryset(
210 fragments, counts=True).filter(
211 category='theme').exclude(pk__in=tags_pks),
214 objects = list(objects)
216 best = random.sample(objects, 3)
220 if not gallery and not objects and len(tags) == 1:
222 if (tag.category in ('theme', 'thing') and PictureArea.tagged.with_any([tag]).exists() or
223 Picture.tagged.with_any([tag]).exists()):
224 return redirect('tagged_object_list_gallery', raw_tags, permanent=False)
226 return render_to_response('catalogue/tagged_object_list.html',
228 'object_list': objects,
229 'categories': categories,
230 'only_shelf': only_shelf,
231 'only_my_shelf': only_my_shelf,
232 'formats_form': forms.DownloadFormatsForm(),
235 'theme_is_set': theme_is_set,
239 context_instance=RequestContext(request))
242 def book_fragments(request, slug, theme_slug):
243 book = get_object_or_404(models.Book, slug=slug)
244 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
245 fragments = models.Fragment.tagged.with_all([theme]).filter(
246 Q(book=book) | Q(book__ancestor=book))
248 return render_to_response('catalogue/book_fragments.html', locals(),
249 context_instance=RequestContext(request))
252 def book_detail(request, slug):
254 book = models.Book.objects.get(slug=slug)
255 except models.Book.DoesNotExist:
256 return pdcounter_views.book_stub_detail(request, slug)
258 tags = book.tags.exclude(category__in=('set', 'theme'))
259 book_children = book.children.all().order_by('parent_number', 'sort_key')
260 return render_to_response('catalogue/book_detail.html', locals(),
261 context_instance=RequestContext(request))
264 def get_audiobooks(book):
266 for m in book.media.filter(type='ogg').order_by().iterator():
267 ogg_files[m.name] = m
272 for mp3 in book.media.filter(type='mp3').iterator():
273 # ogg files are always from the same project
274 meta = mp3.extra_info
275 project = meta.get('project')
278 project = u'CzytamySłuchając'
280 projects.add((project, meta.get('funded_by', '')))
284 ogg = ogg_files.get(mp3.name)
289 audiobooks.append(media)
291 projects = sorted(projects)
292 return audiobooks, projects, have_oggs
295 def player(request, slug):
296 book = get_object_or_404(models.Book, slug=slug)
297 if not book.has_media('mp3'):
300 audiobooks, projects, have_oggs = get_audiobooks(book)
302 extra_info = book.extra_info
304 return render_to_response('catalogue/player.html', locals(),
305 context_instance=RequestContext(request))
308 def book_text(request, slug):
309 book = get_object_or_404(models.Book, slug=slug)
311 if not book.has_html_file():
313 return render_to_response('catalogue/book_text.html', locals(),
314 context_instance=RequestContext(request))
321 def _no_diacritics_regexp(query):
322 """ returns a regexp for searching for a query without diacritics
324 should be locale-aware """
326 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źżŹŻ',
327 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
331 return u"(%s)" % '|'.join(names[l])
332 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
334 def unicode_re_escape(query):
335 """ Unicode-friendly version of re.escape """
336 return re.sub(r'(?u)(\W)', r'\\\1', query)
338 def _word_starts_with(name, prefix):
339 """returns a Q object getting models having `name` contain a word
340 starting with `prefix`
342 We define word characters as alphanumeric and underscore, like in JS.
344 Works for MySQL, PostgreSQL, Oracle.
345 For SQLite, _sqlite* version is substituted for this.
349 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
350 # can't use [[:<:]] (word start),
351 # but we want both `xy` and `(xy` to catch `(xyz)`
352 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
357 def _word_starts_with_regexp(prefix):
358 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
359 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
362 def _sqlite_word_starts_with(name, prefix):
363 """ version of _word_starts_with for SQLite
365 SQLite in Django uses Python re module
368 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
372 if hasattr(settings, 'DATABASES'):
373 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
374 _word_starts_with = _sqlite_word_starts_with
375 elif settings.DATABASE_ENGINE == 'sqlite3':
376 _word_starts_with = _sqlite_word_starts_with
380 def __init__(self, name, view):
383 self.lower = name.lower()
384 self.category = 'application'
386 return reverse(*self._view)
389 App(u'Leśmianator', (u'lesmianator', )),
393 def _tags_starting_with(prefix, user=None):
394 prefix = prefix.lower()
396 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
397 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
399 books = models.Book.objects.filter(_word_starts_with('title', prefix))
400 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
401 if user and user.is_authenticated():
402 tags = tags.filter(~Q(category='set') | Q(user=user))
404 tags = tags.exclude(category='set')
406 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
407 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
410 def _get_result_link(match, tag_list):
411 if isinstance(match, models.Tag):
412 return reverse('catalogue.views.tagged_object_list',
413 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
415 elif isinstance(match, App):
418 return match.get_absolute_url()
421 def _get_result_type(match):
422 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
425 match_type = match.category
429 def books_starting_with(prefix):
430 prefix = prefix.lower()
431 return models.Book.objects.filter(_word_starts_with('title', prefix))
434 def find_best_matches(query, user=None):
435 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
438 - zero elements when nothing is found,
439 - one element when a best result is found,
440 - more then one element on multiple exact matches
442 Raises a ValueError on too short a query.
445 query = query.lower()
447 raise ValueError("query must have at least two characters")
449 result = tuple(_tags_starting_with(query, user))
450 # remove pdcounter stuff
451 book_titles = set(match.pretty_title().lower() for match in result
452 if isinstance(match, models.Book))
453 authors = set(match.name.lower() for match in result
454 if isinstance(match, models.Tag) and match.category == 'author')
455 result = tuple(res for res in result if not (
456 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
457 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
460 exact_matches = tuple(res for res in result if res.name.lower() == query)
464 return tuple(result)[:1]
468 tags = request.GET.get('tags', '')
469 prefix = request.GET.get('q', '')
472 tag_list = models.Tag.get_tag_list(tags)
477 result = find_best_matches(prefix, request.user)
479 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
480 context_instance=RequestContext(request))
483 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
484 elif len(result) > 1:
485 return render_to_response('catalogue/search_multiple_hits.html',
486 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
487 context_instance=RequestContext(request))
489 form = PublishingSuggestForm(initial={"books": prefix + ", "})
490 return render_to_response('catalogue/search_no_hits.html',
491 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
492 context_instance=RequestContext(request))
495 def tags_starting_with(request):
496 prefix = request.GET.get('q', '')
497 # Prefix must have at least 2 characters
499 return HttpResponse('')
502 for tag in _tags_starting_with(prefix, request.user):
503 if not tag.name in tags_list:
504 result += "\n" + tag.name
505 tags_list.append(tag.name)
506 return HttpResponse(result)
508 def json_tags_starting_with(request, callback=None):
510 prefix = request.GET.get('q', '')
511 callback = request.GET.get('callback', '')
512 # Prefix must have at least 2 characters
514 return HttpResponse('')
516 for tag in _tags_starting_with(prefix, request.user):
517 if not tag.name in tags_list:
518 tags_list.append(tag.name)
519 if request.GET.get('mozhint', ''):
520 result = [prefix, tags_list]
522 result = {"matches": tags_list}
523 response = JsonResponse(result, safe=False)
525 response.content = callback + "(" + response.content + ");"
534 def import_book(request):
535 """docstring for import_book"""
536 book_import_form = forms.BookImportForm(request.POST, request.FILES)
537 if book_import_form.is_valid():
539 book_import_form.save()
544 info = sys.exc_info()
545 exception = pprint.pformat(info[1])
546 tb = '\n'.join(traceback.format_tb(info[2]))
547 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
548 return HttpResponse(_("Book imported successfully"))
550 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
555 def book_info(request, id, lang='pl'):
556 book = get_object_or_404(models.Book, id=id)
557 # set language by hand
558 translation.activate(lang)
559 return render_to_response('catalogue/book_info.html', locals(),
560 context_instance=RequestContext(request))
563 def tag_info(request, id):
564 tag = get_object_or_404(models.Tag, id=id)
565 return HttpResponse(tag.description)
568 def download_zip(request, format, slug=None):
570 if format in models.Book.ebook_formats:
571 url = models.Book.zip_format(format)
572 elif format in ('mp3', 'ogg') and slug is not None:
573 book = get_object_or_404(models.Book, slug=slug)
574 url = book.zip_audiobooks(format)
576 raise Http404('No format specified for zip package')
577 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
580 class CustomPDFFormView(AjaxableFormView):
581 form_class = forms.CustomPDFForm
582 title = ugettext_lazy('Download custom PDF')
583 submit = ugettext_lazy('Download')
586 def __call__(self, *args, **kwargs):
587 if settings.NO_CUSTOM_PDF:
588 raise Http404('Custom PDF is disabled')
589 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
591 def form_args(self, request, obj):
592 """Override to parse view args and give additional args to the form."""
595 def get_object(self, request, slug, *args, **kwargs):
596 return get_object_or_404(models.Book, slug=slug)
598 def context_description(self, request, obj):
599 return obj.pretty_title()
608 def book_mini(request, pk, with_link=True):
609 book = get_object_or_404(models.Book, pk=pk)
610 author_str = ", ".join(tag.name
611 for tag in book.tags.filter(category='author'))
612 return render(request, 'catalogue/book_mini_box.html', {
614 'author_str': author_str,
615 'with_link': with_link,
616 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
620 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
621 ('ssify.get_csrf_token',),
622 ('social_tags.likes_book', (ipk,)),
623 ('social_tags.book_shelf_tags', (ipk,)),
624 ))(ssi_expect(pk, int)))
625 def book_short(request, pk):
626 book = get_object_or_404(models.Book, pk=pk)
627 stage_note, stage_note_url = book.stage_note()
628 audiobooks, projects, have_oggs = get_audiobooks(book)
630 return render(request, 'catalogue/book_short.html', {
632 'has_audio': book.has_media('mp3'),
633 'main_link': book.get_absolute_url(),
634 'parents': book.parents(),
635 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
636 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
637 'stage_note': stage_note,
638 'stage_note_url': stage_note_url,
639 'audiobooks': audiobooks,
640 'have_oggs': have_oggs,
644 @ssi_included(get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
646 ('social_tags.choose_cite', [ipk]),
647 ('catalogue_tags.choose_fragment', [ipk], {
648 'unless': V('social_tags.choose_cite', [ipk])}),
649 ))(ssi_expect(pk, int)))
650 def book_wide(request, pk):
651 book = get_object_or_404(models.Book, pk=pk)
652 stage_note, stage_note_url = book.stage_note()
653 extra_info = book.extra_info
654 audiobooks, projects, have_oggs = get_audiobooks(book)
656 return render(request, 'catalogue/book_wide.html', {
658 'has_audio': book.has_media('mp3'),
659 'parents': book.parents(),
660 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
661 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
662 'stage_note': stage_note,
663 'stage_note_url': stage_note_url,
665 'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
666 'extra_info': extra_info,
667 'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
668 'audiobooks': audiobooks,
669 'have_oggs': have_oggs,
674 def fragment_short(request, pk):
675 fragment = get_object_or_404(models.Fragment, pk=pk)
676 return render(request, 'catalogue/fragment_short.html',
677 {'fragment': fragment})
681 def fragment_promo(request, pk):
682 fragment = get_object_or_404(models.Fragment, pk=pk)
683 return render(request, 'catalogue/fragment_promo.html', {
689 def tag_box(request, pk):
690 tag = get_object_or_404(models.Tag, pk=pk)
691 assert tag.category != 'set'
693 return render(request, 'catalogue/tag_box.html', {
699 def collection_box(request, pk):
700 obj = get_object_or_404(models.Collection, pk=pk)
702 return render(request, 'catalogue/collection_box.html', {
707 def tag_catalogue(request, category):
708 if category == 'theme':
709 tags = models.Tag.objects.usage_for_model(
710 models.Fragment, counts=True).filter(category='theme')
712 tags = list(get_top_level_related_tags((), categories=(category,)))
715 best = random.sample(tags, 3)
719 return render(request, 'catalogue/tag_catalogue.html', {
722 'title': constants.CATEGORIES_NAME_PLURAL[category],
726 def collections(request):
727 objects = models.Collection.objects.all()
730 best = random.sample(objects, 3)
734 return render(request, 'catalogue/collections.html', {