1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from collections import OrderedDict
7 from django.conf import settings
8 from django.template.loader import render_to_string
9 from django.shortcuts import get_object_or_404, render, redirect
10 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
11 from django.urls import reverse
12 from django.db.models import Q, QuerySet
13 from django.contrib.auth.decorators import login_required, user_passes_test
14 from django.utils.http import urlquote_plus
15 from django.utils import translation
16 from django.utils.translation import ugettext as _, ugettext_lazy
17 from django.views.decorators.cache import never_cache
19 from ajaxable.utils import AjaxableFormView
20 from club.models import Membership
21 from annoy.models import DynamicTextInsert
22 from pdcounter import views as pdcounter_views
23 from picture.models import Picture, PictureArea
24 from catalogue import constants
25 from catalogue import forms
26 from catalogue.helpers import get_top_level_related_tags
27 from catalogue.models import Book, Collection, Tag, Fragment
28 from catalogue.utils import split_tags
29 from catalogue.models.tag import prefetch_relations
31 staff_required = user_passes_test(lambda user: user.is_staff)
34 def catalogue(request):
35 return render(request, 'catalogue/catalogue.html', {
36 'books': Book.objects.filter(findable=True, parent=None),
37 'pictures': Picture.objects.all(),
38 'collections': Collection.objects.all(),
39 'active_menu_item': 'all_works',
43 def book_list(request, filters=None, template_name='catalogue/book_list.html',
44 nav_template_name='catalogue/snippets/book_list_nav.html',
45 list_template_name='catalogue/snippets/book_list.html'):
46 """ generates a listing of all books, optionally filtered """
47 books_by_author, orphans, books_by_parent = Book.book_list(filters)
48 books_nav = OrderedDict()
49 for tag in books_by_author:
50 if books_by_author[tag]:
51 books_nav.setdefault(tag.sort_key[0], []).append(tag)
52 return render(request, template_name, {
53 'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
54 'rendered_book_list': render_to_string(list_template_name, {
55 'books_by_author': books_by_author,
57 'books_by_parent': books_by_parent,
62 def daisy_list(request):
63 return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
66 def collection(request, slug):
67 coll = get_object_or_404(Collection, slug=slug)
68 return render(request, 'catalogue/collection.html', {'collection': coll})
71 def differentiate_tags(request, tags, ambiguous_slugs):
72 beginning = '/'.join(tag.url_chunk for tag in tags)
73 unparsed = '/'.join(ambiguous_slugs[1:])
75 for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
77 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
82 'catalogue/differentiate_tags.html',
83 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}
87 def object_list(request, objects, fragments=None, related_tags=None, tags=None,
88 list_type='books', extra=None):
91 tag_ids = [tag.pk for tag in tags]
93 related_tag_lists = []
95 related_tag_lists.append(related_tags)
97 related_tag_lists.append(
98 Tag.objects.usage_for_queryset(
100 ).exclude(category='set').exclude(pk__in=tag_ids))
101 if not (extra and extra.get('theme_is_set')):
102 if fragments is None:
103 if list_type == 'gallery':
104 fragments = PictureArea.objects.filter(picture__in=objects)
106 fragments = Fragment.objects.filter(book__in=objects)
107 related_tag_lists.append(
108 Tag.objects.usage_for_queryset(
109 fragments, counts=True
110 ).filter(category='theme').exclude(pk__in=tag_ids)
111 .only('name', 'sort_key', 'category', 'slug'))
112 if isinstance(objects, QuerySet):
113 objects = prefetch_relations(objects, 'author')
115 categories = split_tags(*related_tag_lists)
117 objects = list(objects)
119 if not objects and len(tags) == 1 and list_type == 'books':
120 if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
121 return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
124 best = random.sample(objects, 3)
129 'object_list': objects,
130 'categories': categories,
131 'list_type': list_type,
134 'formats_form': forms.DownloadFormatsForm(),
136 'active_menu_item': list_type,
142 'catalogue/tagged_object_list.html', result,
146 def literature(request):
147 books = Book.objects.filter(parent=None, findable=True)
148 return object_list(request, books, related_tags=get_top_level_related_tags([]))
151 def gallery(request):
152 return object_list(request, Picture.objects.all(), list_type='gallery')
155 def audiobooks(request):
156 audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
157 return object_list(request, audiobooks, list_type='audiobooks', extra={
158 'daisy': Book.objects.filter(findable=True, media__type='daisy').distinct(),
162 class ResponseInstead(Exception):
163 def __init__(self, response):
164 super(ResponseInstead, self).__init__()
165 self.response = response
168 def analyse_tags(request, tag_str):
170 tags = Tag.get_tag_list(tag_str)
171 except Tag.DoesNotExist:
172 # Perhaps the user is asking about an author in Public Domain
173 # counter (they are not represented in tags)
174 chunks = tag_str.split('/')
175 if len(chunks) == 2 and chunks[0] == 'autor':
176 raise ResponseInstead(pdcounter_views.author_detail(request, chunks[1]))
178 except Tag.MultipleObjectsReturned as e:
179 # Ask the user to disambiguate
180 raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
181 except Tag.UrlDeprecationWarning as e:
182 raise ResponseInstead(HttpResponsePermanentRedirect(
183 reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
186 if len(tags) > settings.MAX_TAG_LIST:
188 except AttributeError:
194 def theme_list(request, tags, list_type):
195 shelf_tags = [tag for tag in tags if tag.category == 'set']
196 fragment_tags = [tag for tag in tags if tag.category != 'set']
197 if list_type == 'gallery':
198 fragments = PictureArea.tagged.with_all(fragment_tags)
200 fragments = Fragment.tagged.with_all(fragment_tags)
203 # TODO: Pictures on shelves not supported yet.
204 books = Book.tagged.with_all(shelf_tags).order_by()
205 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
206 elif list_type == 'books':
207 fragments = fragments.filter(book__findable=True)
209 if not fragments and len(tags) == 1 and list_type == 'books':
210 if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
211 return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
213 return object_list(request, fragments, tags=tags, list_type=list_type, extra={
214 'theme_is_set': True,
215 'active_menu_item': 'theme',
219 def tagged_object_list(request, tags, list_type):
221 tags = analyse_tags(request, tags)
222 except ResponseInstead as e:
225 if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
228 if any(tag.category in ('theme', 'thing') for tag in tags):
229 return theme_list(request, tags, list_type=list_type)
231 if list_type == 'books':
232 books = Book.tagged.with_all(tags)
234 if any(tag.category == 'set' for tag in tags):
235 params = {'objects': books}
237 books = books.filter(findable=True)
239 'objects': Book.tagged_top_level(tags).filter(findable=True),
240 'fragments': Fragment.objects.filter(book__in=books),
241 'related_tags': get_top_level_related_tags(tags),
243 elif list_type == 'gallery':
244 params = {'objects': Picture.tagged.with_all(tags)}
245 elif list_type == 'audiobooks':
246 audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
248 'objects': Book.tagged.with_all(tags, audiobooks),
250 'daisy': Book.tagged.with_all(
251 tags, audiobooks.filter(media__type='daisy').distinct()
258 return object_list(request, tags=tags, list_type=list_type, **params)
261 def book_fragments(request, slug, theme_slug):
262 book = get_object_or_404(Book, slug=slug)
263 theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
264 fragments = Fragment.tagged.with_all([theme]).filter(
265 Q(book=book) | Q(book__ancestor=book))
269 'catalogue/book_fragments.html',
273 'fragments': fragments,
274 'active_menu_item': 'books',
279 def book_detail(request, slug):
281 book = Book.objects.get(slug=slug)
282 except Book.DoesNotExist:
283 return pdcounter_views.book_stub_detail(request, slug)
287 'catalogue/book_detail.html',
290 'book_children': book.children.all().order_by('parent_number', 'sort_key'),
291 'active_menu_item': 'books',
295 # używane w publicznym interfejsie
296 def player(request, slug):
297 book = get_object_or_404(Book, slug=slug)
298 if not book.has_media('mp3'):
301 audiobooks, projects = book.get_audiobooks()
305 'catalogue/player.html',
309 'audiobooks': audiobooks,
310 'projects': projects,
314 def book_text(request, slug):
315 book = get_object_or_404(Book, slug=slug)
317 if book.preview and not Membership.is_active_for(request.user):
318 return HttpResponseRedirect(book.get_absolute_url())
320 if not book.has_html_file():
322 with book.html_file.open('r') as f:
325 return render(request, 'catalogue/book_text.html', {
327 'book_text': book_text,
328 'inserts': DynamicTextInsert.get_all(request)
337 def import_book(request):
338 """docstring for import_book"""
339 book_import_form = forms.BookImportForm(request.POST, request.FILES)
340 if book_import_form.is_valid():
342 book_import_form.save()
347 info = sys.exc_info()
348 exception = pprint.pformat(info[1])
349 tb = '\n'.join(traceback.format_tb(info[2]))
351 _("An error occurred: %(exception)s\n\n%(tb)s") % {
352 'exception': exception, 'tb': tb
354 mimetype='text/plain'
356 return HttpResponse(_("Book imported successfully"))
357 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
362 def book_info(request, book_id, lang='pl'):
363 book = get_object_or_404(Book, id=book_id)
364 # set language by hand
365 translation.activate(lang)
366 return render(request, 'catalogue/book_info.html', {'book': book})
369 def tag_info(request, tag_id):
370 tag = get_object_or_404(Tag, id=tag_id)
371 return HttpResponse(tag.description)
375 def embargo_link(request, key, format_, slug):
376 book = get_object_or_404(Book, slug=slug)
377 if format_ not in Book.formats:
379 if key != book.preview_key:
381 media_file = book.get_media(format_)
383 return HttpResponseRedirect(media_file.url)
384 return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
387 def download_zip(request, format, slug=None):
388 if format in Book.ebook_formats:
389 url = Book.zip_format(format)
390 elif format in ('mp3', 'ogg') and slug is not None:
391 book = get_object_or_404(Book, slug=slug)
392 url = book.zip_audiobooks(format)
394 raise Http404('No format specified for zip package')
395 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
398 class CustomPDFFormView(AjaxableFormView):
399 form_class = forms.CustomPDFForm
400 title = ugettext_lazy('Download custom PDF')
401 submit = ugettext_lazy('Download')
402 template = 'catalogue/custom_pdf_form.html'
405 def __call__(self, *args, **kwargs):
406 if settings.NO_CUSTOM_PDF:
407 raise Http404('Custom PDF is disabled')
408 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
410 def form_args(self, request, obj):
411 """Override to parse view args and give additional args to the form."""
414 def validate_object(self, obj, request):
416 if book.preview and not Membership.is_active_for(request.user):
417 return HttpResponseRedirect(book.get_absolute_url())
418 return super(CustomPDFFormView, self).validate_object(obj, request)
420 def get_object(self, request, slug, *args, **kwargs):
421 book = get_object_or_404(Book, slug=slug)
424 def context_description(self, request, obj):
425 return obj.pretty_title()
428 def tag_catalogue(request, category):
429 if category == 'theme':
430 tags = Tag.objects.usage_for_model(
431 Fragment, counts=True).filter(category='theme')
433 tags = list(get_top_level_related_tags((), categories=(category,)))
435 described_tags = [tag for tag in tags if tag.description]
437 if len(described_tags) > 4:
438 best = random.sample(described_tags, 4)
440 best = described_tags
442 return render(request, 'catalogue/tag_catalogue.html', {
445 'title': constants.CATEGORIES_NAME_PLURAL[category],
446 'whole_category': constants.WHOLE_CATEGORY[category],
447 'active_menu_item': 'theme' if category == 'theme' else None,
451 def collections(request):
452 objects = Collection.objects.filter(role='')
455 best = random.sample(list(objects), 3)
459 return render(request, 'catalogue/collections.html', {
465 def ridero_cover(request, slug):
466 from librarian.cover import make_cover
467 wldoc = Book.objects.get(slug=slug).wldocument()
468 cover = make_cover(wldoc.book_info, width=980, bleed=20, format='PNG')
469 response = HttpResponse(content_type="image/png")
474 def get_isbn(request, book_format, slug):
475 book = Book.objects.get(slug=slug)
476 return HttpResponse(book.get_extra_info_json().get('isbn_%s' % book_format))