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/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,
301 # używane w publicznym interfejsie
302 def player(request, slug):
303 book = get_object_or_404(Book, slug=slug)
304 if not book.has_media('mp3'):
307 audiobooks, projects = book.get_audiobooks()
311 'catalogue/player.html',
315 'audiobooks': audiobooks,
316 'projects': projects,
320 def book_text(request, slug):
321 book = get_object_or_404(Book, slug=slug)
323 if book.preview and not Membership.is_active_for(request.user):
324 return HttpResponseRedirect(book.get_absolute_url())
326 if not book.has_html_file():
328 with book.html_file.open('r') as f:
331 return render(request, 'catalogue/book_text.html', {
333 'book_text': book_text,
334 'inserts': DynamicTextInsert.get_all(request)
343 def import_book(request):
344 """docstring for import_book"""
345 book_import_form = forms.BookImportForm(request.POST, request.FILES)
346 if book_import_form.is_valid():
348 book_import_form.save()
353 info = sys.exc_info()
354 exception = pprint.pformat(info[1])
355 tb = '\n'.join(traceback.format_tb(info[2]))
357 _("An error occurred: %(exception)s\n\n%(tb)s") % {
358 'exception': exception, 'tb': tb
360 content_type='text/plain'
362 return HttpResponse(_("Book imported successfully"))
363 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
368 def book_info(request, book_id, lang='pl'):
369 book = get_object_or_404(Book, id=book_id)
370 # set language by hand
371 translation.activate(lang)
372 return render(request, 'catalogue/book_info.html', {'book': book})
375 def tag_info(request, tag_id):
376 tag = get_object_or_404(Tag, id=tag_id)
377 return HttpResponse(tag.description)
381 def embargo_link(request, key, format_, slug):
382 book = get_object_or_404(Book, slug=slug)
383 if format_ not in Book.formats:
385 if key != book.preview_key:
387 media_file = book.get_media(format_)
389 return HttpResponseRedirect(media_file.url)
390 return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
393 def download_zip(request, format, slug=None):
394 if format in Book.ebook_formats:
395 url = Book.zip_format(format)
396 elif format in ('mp3', 'ogg') and slug is not None:
397 book = get_object_or_404(Book, slug=slug)
398 url = book.zip_audiobooks(format)
400 raise Http404('No format specified for zip package')
401 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
404 class CustomPDFFormView(AjaxableFormView):
405 form_class = forms.CustomPDFForm
406 title = ugettext_lazy('Download custom PDF')
407 submit = ugettext_lazy('Download')
408 template = 'catalogue/custom_pdf_form.html'
411 def __call__(self, *args, **kwargs):
412 if settings.NO_CUSTOM_PDF:
413 raise Http404('Custom PDF is disabled')
414 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
416 def form_args(self, request, obj):
417 """Override to parse view args and give additional args to the form."""
420 def validate_object(self, obj, request):
422 if book.preview and not Membership.is_active_for(request.user):
423 return HttpResponseRedirect(book.get_absolute_url())
424 return super(CustomPDFFormView, self).validate_object(obj, request)
426 def get_object(self, request, slug, *args, **kwargs):
427 book = get_object_or_404(Book, slug=slug)
430 def context_description(self, request, obj):
431 return obj.pretty_title()
434 def tag_catalogue(request, category):
435 if category == 'theme':
436 tags = Tag.objects.usage_for_model(
437 Fragment, counts=True).filter(category='theme')
439 tags = list(get_top_level_related_tags((), categories=(category,)))
441 described_tags = [tag for tag in tags if tag.description]
443 if len(described_tags) > 4:
444 best = random.sample(described_tags, 4)
446 best = described_tags
448 return render(request, 'catalogue/tag_catalogue.html', {
451 'title': constants.CATEGORIES_NAME_PLURAL[category],
452 'whole_category': constants.WHOLE_CATEGORY[category],
453 'active_menu_item': 'theme' if category == 'theme' else None,
457 def collections(request):
458 objects = Collection.objects.filter(listed=True)
461 best = random.sample(list(objects), 4)
465 return render(request, 'catalogue/collections.html', {
468 'active_menu_item': 'collections'
472 def ridero_cover(request, slug):
473 from librarian.cover import make_cover
474 wldoc = Book.objects.get(slug=slug).wldocument()
475 cover = make_cover(wldoc.book_info, width=980, bleed=20, format='PNG')
476 response = HttpResponse(content_type="image/png")
481 def get_isbn(request, book_format, slug):
482 book = Book.objects.get(slug=slug)
483 return HttpResponse(book.get_extra_info_json().get('isbn_%s' % book_format))