Tag intersections.
[wolnelektury.git] / src / catalogue / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from collections import OrderedDict
5 import random
6 import re
7 from urllib.parse import quote_plus
8
9 from django.conf import settings
10 from django.template.loader import render_to_string
11 from django.shortcuts import get_object_or_404, render, redirect
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
13 from django.urls import reverse
14 from django.db.models import Q, QuerySet
15 from django.contrib.auth.decorators import login_required, user_passes_test
16 from django.utils import translation
17 from django.utils.translation import gettext as _, gettext_lazy
18 from django.views.decorators.cache import never_cache
19
20 from ajaxable.utils import AjaxableFormView
21 from club.forms import ScheduleForm, DonationStep1Form
22 from club.models import Club
23 from annoy.models import DynamicTextInsert
24 from pdcounter import views as pdcounter_views
25 from picture.models import Picture, PictureArea
26 from catalogue import constants
27 from catalogue import forms
28 from catalogue.helpers import get_top_level_related_tags
29 from catalogue.models import Book, Collection, Tag, Fragment
30 from catalogue.utils import split_tags
31 from catalogue.models.tag import prefetch_relations
32
33 staff_required = user_passes_test(lambda user: user.is_staff)
34
35
36 def catalogue(request):
37     return render(request, 'catalogue/catalogue.html', {
38         'books': Book.objects.filter(findable=True, parent=None),
39         'pictures': Picture.objects.all(),
40         'collections': Collection.objects.filter(listed=True),
41         'active_menu_item': 'all_works',
42     })
43
44
45 def book_list(request, filters=None, template_name='catalogue/book_list.html',
46               nav_template_name='catalogue/snippets/book_list_nav.html',
47               list_template_name='catalogue/snippets/book_list.html'):
48     """ generates a listing of all books, optionally filtered """
49     books_by_author, orphans, books_by_parent = Book.book_list(filters)
50     books_nav = OrderedDict()
51     for tag in books_by_author:
52         if books_by_author[tag]:
53             books_nav.setdefault(tag.sort_key[0], []).append(tag)
54     return render(request, template_name, {
55         'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
56         'rendered_book_list': render_to_string(list_template_name, {
57             'books_by_author': books_by_author,
58             'orphans': orphans,
59             'books_by_parent': books_by_parent,
60         })
61     })
62
63
64 def daisy_list(request):
65     return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
66
67
68 def collection(request, slug):
69     coll = get_object_or_404(Collection, slug=slug)
70     if request.EXPERIMENTS['layout'].value:
71         template_name = 'catalogue/2022/collection.html'
72     else:
73         template_name = 'catalogue/collection.html'
74     return render(request, template_name, {
75         'collection': coll,
76         'active_menu_item': 'collections',
77     })
78
79
80 def differentiate_tags(request, tags, ambiguous_slugs):
81     beginning = '/'.join(tag.url_chunk for tag in tags)
82     unparsed = '/'.join(ambiguous_slugs[1:])
83     options = []
84     for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
85         options.append({
86             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
87             'tags': [tag]
88         })
89     return render(
90         request,
91         'catalogue/differentiate_tags.html',
92         {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}
93     )
94
95
96 def object_list(request, objects, fragments=None, related_tags=None, tags=None,
97                 list_type='books', extra=None):
98     if not tags:
99         tags = []
100     tag_ids = [tag.pk for tag in tags]
101
102     related_tag_lists = []
103     if related_tags:
104         related_tag_lists.append(related_tags)
105     else:
106         related_tag_lists.append(
107             Tag.objects.usage_for_queryset(
108                 objects, counts=True
109             ).exclude(category='set').exclude(pk__in=tag_ids))
110     if not (extra and extra.get('theme_is_set')):
111         if fragments is None:
112             if list_type == 'gallery':
113                 fragments = PictureArea.objects.filter(picture__in=objects)
114             else:
115                 fragments = Fragment.objects.filter(book__in=objects)
116         related_tag_lists.append(
117             Tag.objects.usage_for_queryset(
118                 fragments, counts=True
119             ).filter(category='theme').exclude(pk__in=tag_ids)
120             .only('name', 'sort_key', 'category', 'slug'))
121         if isinstance(objects, QuerySet):
122             objects = prefetch_relations(objects, 'author')
123
124     categories = split_tags(*related_tag_lists)
125     suggest = []
126     for c in ['author', 'epoch', 'kind', 'genre']:
127         if len(categories.get(c, [])) > 1:
128             suggest.extend(categories[c][:4])
129
130     objects = list(objects)
131
132     if not objects and len(tags) == 1 and list_type == 'books':
133         if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
134             return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
135
136     if len(objects) > 3:
137         best = random.sample(objects, 3)
138     else:
139         best = objects
140
141     result = {
142         'object_list': objects,
143         'categories': categories,
144         'suggest': suggest,
145         'list_type': list_type,
146         'tags': tags,
147
148         'formats_form': forms.DownloadFormatsForm(),
149         'best': best,
150         'active_menu_item': list_type,
151     }
152     if extra:
153         result.update(extra)
154
155     is_set = len(tags) == 1 and tags[0].category == 'set'
156     is_theme = len(tags) == 1 and tags[0].category == 'theme'
157     new_layout = request.EXPERIMENTS['layout']
158
159     if is_set and new_layout.value:
160         template = 'catalogue/2022/set_detail.html'
161     elif is_theme and new_layout.value:
162         template = 'catalogue/2022/theme_detail.html'
163     elif new_layout.value:
164         template = 'catalogue/2022/author_detail.html'
165     else:
166         template = 'catalogue/tagged_object_list.html'
167         
168     return render(
169         request, template, result,
170     )
171
172
173 def literature(request):
174     books = Book.objects.filter(parent=None, findable=True)
175     return object_list(request, books, related_tags=get_top_level_related_tags([]))
176
177
178 def gallery(request):
179     return object_list(request, Picture.objects.all(), list_type='gallery')
180
181
182 def audiobooks(request):
183     audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
184     return object_list(request, audiobooks, list_type='audiobooks', extra={
185         'daisy': Book.objects.filter(findable=True, media__type='daisy').distinct(),
186     })
187
188
189 class ResponseInstead(Exception):
190     def __init__(self, response):
191         super(ResponseInstead, self).__init__()
192         self.response = response
193
194
195 def analyse_tags(request, tag_str):
196     try:
197         tags = Tag.get_tag_list(tag_str)
198     except Tag.DoesNotExist:
199         # Perhaps the user is asking about an author in Public Domain
200         # counter (they are not represented in tags)
201         chunks = tag_str.split('/')
202         if len(chunks) == 2 and chunks[0] == 'autor':
203             raise ResponseInstead(pdcounter_views.author_detail(request, chunks[1]))
204         raise Http404
205     except Tag.MultipleObjectsReturned as e:
206         # Ask the user to disambiguate
207         raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
208     except Tag.UrlDeprecationWarning as e:
209         raise ResponseInstead(HttpResponsePermanentRedirect(
210             reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
211
212     try:
213         if len(tags) > settings.MAX_TAG_LIST:
214             raise Http404
215     except AttributeError:
216         pass
217
218     return tags
219
220
221 def theme_list(request, tags, list_type):
222     shelf_tags = [tag for tag in tags if tag.category == 'set']
223     fragment_tags = [tag for tag in tags if tag.category != 'set']
224     if list_type == 'gallery':
225         fragments = PictureArea.tagged.with_all(fragment_tags)
226     else:
227         fragments = Fragment.tagged.with_all(fragment_tags)
228
229     if shelf_tags:
230         # TODO: Pictures on shelves not supported yet.
231         books = Book.tagged.with_all(shelf_tags).order_by()
232         fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
233     elif list_type == 'books':
234         fragments = fragments.filter(book__findable=True)
235
236     if not fragments and len(tags) == 1 and list_type == 'books':
237         if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
238             return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
239
240     return object_list(request, fragments, tags=tags, list_type=list_type, extra={
241         'theme_is_set': True,
242         'active_menu_item': 'theme',
243     })
244
245
246 def tagged_object_list(request, tags, list_type):
247     try:
248         tags = analyse_tags(request, tags)
249     except ResponseInstead as e:
250         return e.response
251
252     if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
253         raise Http404
254
255     if any(tag.category in ('theme', 'thing') for tag in tags):
256         return theme_list(request, tags, list_type=list_type)
257
258     if list_type == 'books':
259         books = Book.tagged.with_all(tags)
260
261         if any(tag.category == 'set' for tag in tags):
262             params = {'objects': books}
263         else:
264             books = books.filter(findable=True)
265             params = {
266                 'objects': Book.tagged_top_level(tags).filter(findable=True),
267                 'fragments': Fragment.objects.filter(book__in=books),
268                 'related_tags': get_top_level_related_tags(tags),
269             }
270     elif list_type == 'gallery':
271         params = {'objects': Picture.tagged.with_all(tags)}
272     elif list_type == 'audiobooks':
273         audiobooks = Book.objects.filter(findable=True, media__type__in=('mp3', 'ogg')).distinct()
274         params = {
275             'objects': Book.tagged.with_all(tags, audiobooks),
276             'extra': {
277                 'daisy': Book.tagged.with_all(
278                     tags, audiobooks.filter(media__type='daisy').distinct()
279                 ),
280             }
281         }
282     else:
283         raise Http404
284
285     return object_list(request, tags=tags, list_type=list_type, **params)
286
287
288 def book_fragments(request, slug, theme_slug):
289     book = get_object_or_404(Book, slug=slug)
290     theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
291     fragments = Fragment.tagged.with_all([theme]).filter(
292         Q(book=book) | Q(book__ancestor=book))
293
294     return render(
295         request,
296         'catalogue/book_fragments.html',
297         {
298             'book': book,
299             'theme': theme,
300             'fragments': fragments,
301             'active_menu_item': 'books',
302         })
303
304
305 @never_cache
306 def book_detail(request, slug):
307     try:
308         book = Book.objects.get(slug=slug)
309     except Book.DoesNotExist:
310         return pdcounter_views.book_stub_detail(request, slug)
311
312     new_layout = request.EXPERIMENTS['layout']
313     
314     return render(
315         request,
316         'catalogue/2022/book_detail.html' if new_layout.value else 'catalogue/book_detail.html',
317         {
318             'book': book,
319             'accessible': book.is_accessible_to(request.user),
320             'book_children': book.children.all().order_by('parent_number', 'sort_key'),
321             'active_menu_item': 'books',
322             'club_form': ScheduleForm() if book.preview else None,
323             'club': Club.objects.first() if book.preview else None,
324             'donation_form': DonationStep1Form(),
325
326             'EXPERIMENTS_SWITCHABLE_layout': True,
327         })
328
329
330 # używane w publicznym interfejsie
331 def player(request, slug):
332     book = get_object_or_404(Book, slug=slug)
333     if not book.has_media('mp3'):
334         raise Http404
335
336     audiobooks, projects, total_duration = book.get_audiobooks()
337
338     return render(
339         request,
340         'catalogue/player.html',
341         {
342             'book': book,
343             'audiobook': '',
344             'audiobooks': audiobooks,
345             'projects': projects,
346         })
347
348
349 def book_text(request, slug):
350     book = get_object_or_404(Book, slug=slug)
351
352     if not book.is_accessible_to(request.user):
353         return HttpResponseRedirect(book.get_absolute_url())
354
355     if not book.has_html_file():
356         raise Http404
357     with book.html_file.open('r') as f:
358         book_text = f.read()
359
360     return render(request, 'catalogue/book_text.html', {
361         'book': book,
362         'book_text': book_text,
363         'inserts': DynamicTextInsert.get_all(request)
364     })
365
366
367 # =========
368 # = Admin =
369 # =========
370 @login_required
371 @staff_required
372 def import_book(request):
373     """docstring for import_book"""
374     book_import_form = forms.BookImportForm(request.POST, request.FILES)
375     if book_import_form.is_valid():
376         try:
377             book_import_form.save()
378         except:
379             import sys
380             import pprint
381             import traceback
382             info = sys.exc_info()
383             exception = pprint.pformat(info[1])
384             tb = '\n'.join(traceback.format_tb(info[2]))
385             return HttpResponse(
386                 _("An error occurred: %(exception)s\n\n%(tb)s") % {
387                     'exception': exception, 'tb': tb
388                 },
389                 content_type='text/plain'
390             )
391         return HttpResponse(_("Book imported successfully"))
392     return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
393
394
395 # info views for API
396
397 def book_info(request, book_id, lang='pl'):
398     book = get_object_or_404(Book, id=book_id)
399     # set language by hand
400     translation.activate(lang)
401     return render(request, 'catalogue/book_info.html', {'book': book})
402
403
404 def tag_info(request, tag_id):
405     tag = get_object_or_404(Tag, id=tag_id)
406     return HttpResponse(tag.description)
407
408
409 @never_cache
410 def embargo_link(request, key, format_, slug):
411     book = get_object_or_404(Book, slug=slug)
412     if format_ not in Book.formats:
413         raise Http404
414     if key != book.preview_key:
415         raise Http404
416     media_file = book.get_media(format_)
417     if not book.preview:
418         return HttpResponseRedirect(media_file.url)
419     return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
420
421
422 def download_zip(request, file_format=None, media_format=None, slug=None):
423     if file_format:
424         url = Book.zip_format(file_format)
425     elif media_format and slug is not None:
426         book = get_object_or_404(Book, slug=slug)
427         url = book.zip_audiobooks(media_format)
428     else:
429         raise Http404('No format specified for zip package')
430     return HttpResponseRedirect(quote_plus(settings.MEDIA_URL + url, safe='/?='))
431
432
433 class CustomPDFFormView(AjaxableFormView):
434     form_class = forms.CustomPDFForm
435     title = gettext_lazy('Download custom PDF')
436     submit = gettext_lazy('Download')
437     template = 'catalogue/custom_pdf_form.html'
438     honeypot = True
439
440     def __call__(self, *args, **kwargs):
441         if settings.NO_CUSTOM_PDF:
442             raise Http404('Custom PDF is disabled')
443         return super(CustomPDFFormView, self).__call__(*args, **kwargs)
444
445     def form_args(self, request, obj):
446         """Override to parse view args and give additional args to the form."""
447         return (obj,), {}
448
449     def validate_object(self, obj, request):
450         book = obj
451         if not book.is_accessible_to(request.user):
452             return HttpResponseRedirect(book.get_absolute_url())
453         return super(CustomPDFFormView, self).validate_object(obj, request)
454
455     def get_object(self, request, slug, *args, **kwargs):
456         book = get_object_or_404(Book, slug=slug)
457         return book
458
459     def context_description(self, request, obj):
460         return obj.pretty_title()
461
462
463 def tag_catalogue(request, category):
464     if category == 'theme':
465         tags = Tag.objects.usage_for_model(
466             Fragment, counts=True).filter(category='theme')
467     else:
468         tags = list(get_top_level_related_tags((), categories=(category,)))
469
470     described_tags = [tag for tag in tags if tag.description]
471
472     if len(described_tags) > 4:
473         best = random.sample(described_tags, 4)
474     else:
475         best = described_tags
476
477     return render(request, 'catalogue/tag_catalogue.html', {
478         'tags': tags,
479         'best': best,
480         'title': constants.CATEGORIES_NAME_PLURAL[category],
481         'whole_category': constants.WHOLE_CATEGORY[category],
482         'active_menu_item': 'theme' if category == 'theme' else None,
483     })
484
485
486 def collections(request):
487     objects = Collection.objects.filter(listed=True)
488
489     if len(objects) > 3:
490         best = random.sample(list(objects), 4)
491     else:
492         best = objects
493
494     if request.EXPERIMENTS['layout'].value:
495         template_name = 'catalogue/2022/collections.html'
496     else:
497         template_name = 'catalogue/collections.html'
498
499     return render(request, template_name, {
500         'objects': objects,
501         'best': best,
502         'active_menu_item': 'collections'
503     })
504
505
506 def ridero_cover(request, slug):
507     from librarian.cover import make_cover
508     wldoc = Book.objects.get(slug=slug).wldocument()
509     cover = make_cover(wldoc.book_info, width=980, bleed=20, format='PNG')
510     response = HttpResponse(content_type="image/png")
511     cover.save(response)
512     return response
513
514
515 def get_isbn(request, book_format, slug):
516     book = Book.objects.get(slug=slug)
517     return HttpResponse(book.get_extra_info_json().get('isbn_%s' % book_format))