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.all(),
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', {'collection': coll})
72 def differentiate_tags(request, tags, ambiguous_slugs):
73 beginning = '/'.join(tag.url_chunk for tag in tags)
74 unparsed = '/'.join(ambiguous_slugs[1:])
76 for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
78 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
83 'catalogue/differentiate_tags.html',
84 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}
88 def object_list(request, objects, fragments=None, related_tags=None, tags=None,
89 list_type='books', extra=None):
92 tag_ids = [tag.pk for tag in tags]
94 related_tag_lists = []
96 related_tag_lists.append(related_tags)
98 related_tag_lists.append(
99 Tag.objects.usage_for_queryset(
101 ).exclude(category='set').exclude(pk__in=tag_ids))
102 if not (extra and extra.get('theme_is_set')):
103 if fragments is None:
104 if list_type == 'gallery':
105 fragments = PictureArea.objects.filter(picture__in=objects)
107 fragments = Fragment.objects.filter(book__in=objects)
108 related_tag_lists.append(
109 Tag.objects.usage_for_queryset(
110 fragments, counts=True
111 ).filter(category='theme').exclude(pk__in=tag_ids)
112 .only('name', 'sort_key', 'category', 'slug'))
113 if isinstance(objects, QuerySet):
114 objects = prefetch_relations(objects, 'author')
116 categories = split_tags(*related_tag_lists)
118 objects = list(objects)
120 if not objects and len(tags) == 1 and list_type == 'books':
121 if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
122 return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
125 best = random.sample(objects, 3)
130 'object_list': objects,
131 'categories': categories,
132 'list_type': list_type,
135 'formats_form': forms.DownloadFormatsForm(),
137 'active_menu_item': list_type,
143 'catalogue/tagged_object_list.html', result,
147 def literature(request):
148 books = Book.objects.filter(parent=None, findable=True)
149 return object_list(request, books, related_tags=get_top_level_related_tags([]))
152 def gallery(request):
153 return object_list(request, Picture.objects.all(), list_type='gallery')
156 def audiobooks(request):
157 audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
158 return object_list(request, audiobooks, list_type='audiobooks', extra={
159 'daisy': Book.objects.filter(findable=True, media__type='daisy').distinct(),
163 class ResponseInstead(Exception):
164 def __init__(self, response):
165 super(ResponseInstead, self).__init__()
166 self.response = response
169 def analyse_tags(request, tag_str):
171 tags = Tag.get_tag_list(tag_str)
172 except Tag.DoesNotExist:
173 # Perhaps the user is asking about an author in Public Domain
174 # counter (they are not represented in tags)
175 chunks = tag_str.split('/')
176 if len(chunks) == 2 and chunks[0] == 'autor':
177 raise ResponseInstead(pdcounter_views.author_detail(request, chunks[1]))
179 except Tag.MultipleObjectsReturned as e:
180 # Ask the user to disambiguate
181 raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
182 except Tag.UrlDeprecationWarning as e:
183 raise ResponseInstead(HttpResponsePermanentRedirect(
184 reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
187 if len(tags) > settings.MAX_TAG_LIST:
189 except AttributeError:
195 def theme_list(request, tags, list_type):
196 shelf_tags = [tag for tag in tags if tag.category == 'set']
197 fragment_tags = [tag for tag in tags if tag.category != 'set']
198 if list_type == 'gallery':
199 fragments = PictureArea.tagged.with_all(fragment_tags)
201 fragments = Fragment.tagged.with_all(fragment_tags)
204 # TODO: Pictures on shelves not supported yet.
205 books = Book.tagged.with_all(shelf_tags).order_by()
206 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
207 elif list_type == 'books':
208 fragments = fragments.filter(book__findable=True)
210 if not fragments and len(tags) == 1 and list_type == 'books':
211 if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
212 return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
214 return object_list(request, fragments, tags=tags, list_type=list_type, extra={
215 'theme_is_set': True,
216 'active_menu_item': 'theme',
220 def tagged_object_list(request, tags, list_type):
222 tags = analyse_tags(request, tags)
223 except ResponseInstead as e:
226 if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
229 if any(tag.category in ('theme', 'thing') for tag in tags):
230 return theme_list(request, tags, list_type=list_type)
232 if list_type == 'books':
233 books = Book.tagged.with_all(tags)
235 if any(tag.category == 'set' for tag in tags):
236 params = {'objects': books}
238 books = books.filter(findable=True)
240 'objects': Book.tagged_top_level(tags).filter(findable=True),
241 'fragments': Fragment.objects.filter(book__in=books),
242 'related_tags': get_top_level_related_tags(tags),
244 elif list_type == 'gallery':
245 params = {'objects': Picture.tagged.with_all(tags)}
246 elif list_type == 'audiobooks':
247 audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
249 'objects': Book.tagged.with_all(tags, audiobooks),
251 'daisy': Book.tagged.with_all(
252 tags, audiobooks.filter(media__type='daisy').distinct()
259 return object_list(request, tags=tags, list_type=list_type, **params)
262 def book_fragments(request, slug, theme_slug):
263 book = get_object_or_404(Book, slug=slug)
264 theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
265 fragments = Fragment.tagged.with_all([theme]).filter(
266 Q(book=book) | Q(book__ancestor=book))
270 'catalogue/book_fragments.html',
274 'fragments': fragments,
275 'active_menu_item': 'books',
280 def book_detail(request, slug):
282 book = Book.objects.get(slug=slug)
283 except Book.DoesNotExist:
284 return pdcounter_views.book_stub_detail(request, slug)
288 'catalogue/book_detail.html',
291 'book_children': book.children.all().order_by('parent_number', 'sort_key'),
292 'active_menu_item': 'books',
293 'club_form': ScheduleForm() if book.preview else None,
294 'club': Club.objects.first() if book.preview else None,
298 # używane w publicznym interfejsie
299 def player(request, slug):
300 book = get_object_or_404(Book, slug=slug)
301 if not book.has_media('mp3'):
304 audiobooks, projects = book.get_audiobooks()
308 'catalogue/player.html',
312 'audiobooks': audiobooks,
313 'projects': projects,
317 def book_text(request, slug):
318 book = get_object_or_404(Book, slug=slug)
320 if book.preview and not Membership.is_active_for(request.user):
321 return HttpResponseRedirect(book.get_absolute_url())
323 if not book.has_html_file():
325 with book.html_file.open('r') as f:
328 return render(request, 'catalogue/book_text.html', {
330 'book_text': book_text,
331 'inserts': DynamicTextInsert.get_all(request)
340 def import_book(request):
341 """docstring for import_book"""
342 book_import_form = forms.BookImportForm(request.POST, request.FILES)
343 if book_import_form.is_valid():
345 book_import_form.save()
350 info = sys.exc_info()
351 exception = pprint.pformat(info[1])
352 tb = '\n'.join(traceback.format_tb(info[2]))
354 _("An error occurred: %(exception)s\n\n%(tb)s") % {
355 'exception': exception, 'tb': tb
357 content_type='text/plain'
359 return HttpResponse(_("Book imported successfully"))
360 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
365 def book_info(request, book_id, lang='pl'):
366 book = get_object_or_404(Book, id=book_id)
367 # set language by hand
368 translation.activate(lang)
369 return render(request, 'catalogue/book_info.html', {'book': book})
372 def tag_info(request, tag_id):
373 tag = get_object_or_404(Tag, id=tag_id)
374 return HttpResponse(tag.description)
378 def embargo_link(request, key, format_, slug):
379 book = get_object_or_404(Book, slug=slug)
380 if format_ not in Book.formats:
382 if key != book.preview_key:
384 media_file = book.get_media(format_)
386 return HttpResponseRedirect(media_file.url)
387 return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
390 def download_zip(request, format, slug=None):
391 if format in Book.ebook_formats:
392 url = Book.zip_format(format)
393 elif format in ('mp3', 'ogg') and slug is not None:
394 book = get_object_or_404(Book, slug=slug)
395 url = book.zip_audiobooks(format)
397 raise Http404('No format specified for zip package')
398 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
401 class CustomPDFFormView(AjaxableFormView):
402 form_class = forms.CustomPDFForm
403 title = ugettext_lazy('Download custom PDF')
404 submit = ugettext_lazy('Download')
405 template = 'catalogue/custom_pdf_form.html'
408 def __call__(self, *args, **kwargs):
409 if settings.NO_CUSTOM_PDF:
410 raise Http404('Custom PDF is disabled')
411 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
413 def form_args(self, request, obj):
414 """Override to parse view args and give additional args to the form."""
417 def validate_object(self, obj, request):
419 if book.preview and not Membership.is_active_for(request.user):
420 return HttpResponseRedirect(book.get_absolute_url())
421 return super(CustomPDFFormView, self).validate_object(obj, request)
423 def get_object(self, request, slug, *args, **kwargs):
424 book = get_object_or_404(Book, slug=slug)
427 def context_description(self, request, obj):
428 return obj.pretty_title()
431 def tag_catalogue(request, category):
432 if category == 'theme':
433 tags = Tag.objects.usage_for_model(
434 Fragment, counts=True).filter(category='theme')
436 tags = list(get_top_level_related_tags((), categories=(category,)))
438 described_tags = [tag for tag in tags if tag.description]
440 if len(described_tags) > 4:
441 best = random.sample(described_tags, 4)
443 best = described_tags
445 return render(request, 'catalogue/tag_catalogue.html', {
448 'title': constants.CATEGORIES_NAME_PLURAL[category],
449 'whole_category': constants.WHOLE_CATEGORY[category],
450 'active_menu_item': 'theme' if category == 'theme' else None,
454 def collections(request):
455 objects = Collection.objects.all()
458 best = random.sample(list(objects), 3)
462 return render(request, 'catalogue/collections.html', {
468 def ridero_cover(request, slug):
469 from librarian.cover import make_cover
470 wldoc = Book.objects.get(slug=slug).wldocument()
471 cover = make_cover(wldoc.book_info, width=980, bleed=20, format='PNG')
472 response = HttpResponse(content_type="image/png")
477 def get_isbn(request, book_format, slug):
478 book = Book.objects.get(slug=slug)
479 return HttpResponse(book.get_extra_info_json().get('isbn_%s' % book_format))