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.forms import ScheduleForm
21 from club.models import Club, Membership
22 from annoy.models import DynamicTextInsert
23 from pdcounter import views as pdcounter_views
24 from picture.models import Picture, PictureArea
25 from catalogue import constants
26 from catalogue import forms
27 from catalogue.helpers import get_top_level_related_tags
28 from catalogue.models import Book, Collection, Tag, Fragment
29 from catalogue.utils import split_tags
30 from catalogue.models.tag import prefetch_relations
32 staff_required = user_passes_test(lambda user: user.is_staff)
35 def catalogue(request):
36 return render(request, 'catalogue/catalogue.html', {
37 'books': Book.objects.filter(findable=True, parent=None),
38 'pictures': Picture.objects.all(),
39 'collections': Collection.objects.filter(listed=True),
40 'active_menu_item': 'all_works',
44 def book_list(request, filters=None, template_name='catalogue/book_list.html',
45 nav_template_name='catalogue/snippets/book_list_nav.html',
46 list_template_name='catalogue/snippets/book_list.html'):
47 """ generates a listing of all books, optionally filtered """
48 books_by_author, orphans, books_by_parent = Book.book_list(filters)
49 books_nav = OrderedDict()
50 for tag in books_by_author:
51 if books_by_author[tag]:
52 books_nav.setdefault(tag.sort_key[0], []).append(tag)
53 return render(request, template_name, {
54 'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
55 'rendered_book_list': render_to_string(list_template_name, {
56 'books_by_author': books_by_author,
58 'books_by_parent': books_by_parent,
63 def daisy_list(request):
64 return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
67 def collection(request, slug):
68 coll = get_object_or_404(Collection, slug=slug)
69 return render(request, 'catalogue/collection.html', {
71 'active_menu_item': 'collections',
75 def differentiate_tags(request, tags, ambiguous_slugs):
76 beginning = '/'.join(tag.url_chunk for tag in tags)
77 unparsed = '/'.join(ambiguous_slugs[1:])
79 for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
81 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
86 'catalogue/differentiate_tags.html',
87 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}
91 def object_list(request, objects, fragments=None, related_tags=None, tags=None,
92 list_type='books', extra=None):
95 tag_ids = [tag.pk for tag in tags]
97 related_tag_lists = []
99 related_tag_lists.append(related_tags)
101 related_tag_lists.append(
102 Tag.objects.usage_for_queryset(
104 ).exclude(category='set').exclude(pk__in=tag_ids))
105 if not (extra and extra.get('theme_is_set')):
106 if fragments is None:
107 if list_type == 'gallery':
108 fragments = PictureArea.objects.filter(picture__in=objects)
110 fragments = Fragment.objects.filter(book__in=objects)
111 related_tag_lists.append(
112 Tag.objects.usage_for_queryset(
113 fragments, counts=True
114 ).filter(category='theme').exclude(pk__in=tag_ids)
115 .only('name', 'sort_key', 'category', 'slug'))
116 if isinstance(objects, QuerySet):
117 objects = prefetch_relations(objects, 'author')
119 categories = split_tags(*related_tag_lists)
121 objects = list(objects)
123 if not objects and len(tags) == 1 and list_type == 'books':
124 if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
125 return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
128 best = random.sample(objects, 3)
133 'object_list': objects,
134 'categories': categories,
135 'list_type': list_type,
138 'formats_form': forms.DownloadFormatsForm(),
140 'active_menu_item': list_type,
146 'catalogue/tagged_object_list.html', result,
150 def literature(request):
151 books = Book.objects.filter(parent=None, findable=True)
152 return object_list(request, books, related_tags=get_top_level_related_tags([]))
155 def gallery(request):
156 return object_list(request, Picture.objects.all(), list_type='gallery')
159 def audiobooks(request):
160 audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
161 return object_list(request, audiobooks, list_type='audiobooks', extra={
162 'daisy': Book.objects.filter(findable=True, media__type='daisy').distinct(),
166 class ResponseInstead(Exception):
167 def __init__(self, response):
168 super(ResponseInstead, self).__init__()
169 self.response = response
172 def analyse_tags(request, tag_str):
174 tags = Tag.get_tag_list(tag_str)
175 except Tag.DoesNotExist:
176 # Perhaps the user is asking about an author in Public Domain
177 # counter (they are not represented in tags)
178 chunks = tag_str.split('/')
179 if len(chunks) == 2 and chunks[0] == 'autor':
180 raise ResponseInstead(pdcounter_views.author_detail(request, chunks[1]))
182 except Tag.MultipleObjectsReturned as e:
183 # Ask the user to disambiguate
184 raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
185 except Tag.UrlDeprecationWarning as e:
186 raise ResponseInstead(HttpResponsePermanentRedirect(
187 reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
190 if len(tags) > settings.MAX_TAG_LIST:
192 except AttributeError:
198 def theme_list(request, tags, list_type):
199 shelf_tags = [tag for tag in tags if tag.category == 'set']
200 fragment_tags = [tag for tag in tags if tag.category != 'set']
201 if list_type == 'gallery':
202 fragments = PictureArea.tagged.with_all(fragment_tags)
204 fragments = Fragment.tagged.with_all(fragment_tags)
207 # TODO: Pictures on shelves not supported yet.
208 books = Book.tagged.with_all(shelf_tags).order_by()
209 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
210 elif list_type == 'books':
211 fragments = fragments.filter(book__findable=True)
213 if not fragments and len(tags) == 1 and list_type == 'books':
214 if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
215 return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
217 return object_list(request, fragments, tags=tags, list_type=list_type, extra={
218 'theme_is_set': True,
219 'active_menu_item': 'theme',
223 def tagged_object_list(request, tags, list_type):
225 tags = analyse_tags(request, tags)
226 except ResponseInstead as e:
229 if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
232 if any(tag.category in ('theme', 'thing') for tag in tags):
233 return theme_list(request, tags, list_type=list_type)
235 if list_type == 'books':
236 books = Book.tagged.with_all(tags)
238 if any(tag.category == 'set' for tag in tags):
239 params = {'objects': books}
241 books = books.filter(findable=True)
243 'objects': Book.tagged_top_level(tags).filter(findable=True),
244 'fragments': Fragment.objects.filter(book__in=books),
245 'related_tags': get_top_level_related_tags(tags),
247 elif list_type == 'gallery':
248 params = {'objects': Picture.tagged.with_all(tags)}
249 elif list_type == 'audiobooks':
250 audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
252 'objects': Book.tagged.with_all(tags, audiobooks),
254 'daisy': Book.tagged.with_all(
255 tags, audiobooks.filter(media__type='daisy').distinct()
262 return object_list(request, tags=tags, list_type=list_type, **params)
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))
273 'catalogue/book_fragments.html',
277 'fragments': fragments,
278 'active_menu_item': 'books',
283 def book_detail(request, slug):
285 book = Book.objects.get(slug=slug)
286 except Book.DoesNotExist:
287 return pdcounter_views.book_stub_detail(request, slug)
291 'catalogue/2021/book_detail.html' if request.EXPERIMENTS['layout'] == 'new' else 'catalogue/book_detail.html',
294 'book_children': book.children.all().order_by('parent_number', 'sort_key'),
295 'active_menu_item': 'books',
296 'club_form': ScheduleForm() if book.preview else None,
297 'club': Club.objects.first() if book.preview else None,
299 'EXPERIMENTS_SWITCHABLE_layout': True,
303 # używane w publicznym interfejsie
304 def player(request, slug):
305 book = get_object_or_404(Book, slug=slug)
306 if not book.has_media('mp3'):
309 audiobooks, projects = book.get_audiobooks()
313 'catalogue/player.html',
317 'audiobooks': audiobooks,
318 'projects': projects,
322 def book_text(request, slug):
323 book = get_object_or_404(Book, slug=slug)
325 if book.preview and not Membership.is_active_for(request.user):
326 return HttpResponseRedirect(book.get_absolute_url())
328 if not book.has_html_file():
330 with book.html_file.open('r') as f:
333 return render(request, 'catalogue/book_text.html', {
335 'book_text': book_text,
336 'inserts': DynamicTextInsert.get_all(request)
345 def import_book(request):
346 """docstring for import_book"""
347 book_import_form = forms.BookImportForm(request.POST, request.FILES)
348 if book_import_form.is_valid():
350 book_import_form.save()
355 info = sys.exc_info()
356 exception = pprint.pformat(info[1])
357 tb = '\n'.join(traceback.format_tb(info[2]))
359 _("An error occurred: %(exception)s\n\n%(tb)s") % {
360 'exception': exception, 'tb': tb
362 content_type='text/plain'
364 return HttpResponse(_("Book imported successfully"))
365 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
370 def book_info(request, book_id, lang='pl'):
371 book = get_object_or_404(Book, id=book_id)
372 # set language by hand
373 translation.activate(lang)
374 return render(request, 'catalogue/book_info.html', {'book': book})
377 def tag_info(request, tag_id):
378 tag = get_object_or_404(Tag, id=tag_id)
379 return HttpResponse(tag.description)
383 def embargo_link(request, key, format_, slug):
384 book = get_object_or_404(Book, slug=slug)
385 if format_ not in Book.formats:
387 if key != book.preview_key:
389 media_file = book.get_media(format_)
391 return HttpResponseRedirect(media_file.url)
392 return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
395 def download_zip(request, format, slug=None):
396 if format in Book.ebook_formats:
397 url = Book.zip_format(format)
398 elif format in ('mp3', 'ogg') and slug is not None:
399 book = get_object_or_404(Book, slug=slug)
400 url = book.zip_audiobooks(format)
402 raise Http404('No format specified for zip package')
403 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
406 class CustomPDFFormView(AjaxableFormView):
407 form_class = forms.CustomPDFForm
408 title = ugettext_lazy('Download custom PDF')
409 submit = ugettext_lazy('Download')
410 template = 'catalogue/custom_pdf_form.html'
413 def __call__(self, *args, **kwargs):
414 if settings.NO_CUSTOM_PDF:
415 raise Http404('Custom PDF is disabled')
416 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
418 def form_args(self, request, obj):
419 """Override to parse view args and give additional args to the form."""
422 def validate_object(self, obj, request):
424 if book.preview and not Membership.is_active_for(request.user):
425 return HttpResponseRedirect(book.get_absolute_url())
426 return super(CustomPDFFormView, self).validate_object(obj, request)
428 def get_object(self, request, slug, *args, **kwargs):
429 book = get_object_or_404(Book, slug=slug)
432 def context_description(self, request, obj):
433 return obj.pretty_title()
436 def tag_catalogue(request, category):
437 if category == 'theme':
438 tags = Tag.objects.usage_for_model(
439 Fragment, counts=True).filter(category='theme')
441 tags = list(get_top_level_related_tags((), categories=(category,)))
443 described_tags = [tag for tag in tags if tag.description]
445 if len(described_tags) > 4:
446 best = random.sample(described_tags, 4)
448 best = described_tags
450 return render(request, 'catalogue/tag_catalogue.html', {
453 'title': constants.CATEGORIES_NAME_PLURAL[category],
454 'whole_category': constants.WHOLE_CATEGORY[category],
455 'active_menu_item': 'theme' if category == 'theme' else None,
459 def collections(request):
460 objects = Collection.objects.filter(listed=True)
463 best = random.sample(list(objects), 4)
467 return render(request, 'catalogue/collections.html', {
470 'active_menu_item': 'collections'
474 def ridero_cover(request, slug):
475 from librarian.cover import make_cover
476 wldoc = Book.objects.get(slug=slug).wldocument()
477 cover = make_cover(wldoc.book_info, width=980, bleed=20, format='PNG')
478 response = HttpResponse(content_type="image/png")
483 def get_isbn(request, book_format, slug):
484 book = Book.objects.get(slug=slug)
485 return HttpResponse(book.get_extra_info_json().get('isbn_%s' % book_format))