Filtering search results.
[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
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
18
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
31
32 staff_required = user_passes_test(lambda user: user.is_staff)
33
34
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',
41     })
42
43
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,
57             'orphans': orphans,
58             'books_by_parent': books_by_parent,
59         })
60     })
61
62
63 def daisy_list(request):
64     return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
65
66
67 def collection(request, slug):
68     coll = get_object_or_404(Collection, slug=slug)
69     return render(request, 'catalogue/collection.html', {
70         'collection': coll,
71         'active_menu_item': 'collections',
72     })
73
74
75 def differentiate_tags(request, tags, ambiguous_slugs):
76     beginning = '/'.join(tag.url_chunk for tag in tags)
77     unparsed = '/'.join(ambiguous_slugs[1:])
78     options = []
79     for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
80         options.append({
81             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
82             'tags': [tag]
83         })
84     return render(
85         request,
86         'catalogue/differentiate_tags.html',
87         {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}
88     )
89
90
91 def object_list(request, objects, fragments=None, related_tags=None, tags=None,
92                 list_type='books', extra=None):
93     if not tags:
94         tags = []
95     tag_ids = [tag.pk for tag in tags]
96
97     related_tag_lists = []
98     if related_tags:
99         related_tag_lists.append(related_tags)
100     else:
101         related_tag_lists.append(
102             Tag.objects.usage_for_queryset(
103                 objects, counts=True
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)
109             else:
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')
118
119     categories = split_tags(*related_tag_lists)
120
121     objects = list(objects)
122
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))
126
127     if len(objects) > 3:
128         best = random.sample(objects, 3)
129     else:
130         best = objects
131
132     result = {
133         'object_list': objects,
134         'categories': categories,
135         'list_type': list_type,
136         'tags': tags,
137
138         'formats_form': forms.DownloadFormatsForm(),
139         'best': best,
140         'active_menu_item': list_type,
141     }
142     if extra:
143         result.update(extra)
144     return render(
145         request,
146         'catalogue/tagged_object_list.html', result,
147     )
148
149
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([]))
153
154
155 def gallery(request):
156     return object_list(request, Picture.objects.all(), list_type='gallery')
157
158
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(),
163     })
164
165
166 class ResponseInstead(Exception):
167     def __init__(self, response):
168         super(ResponseInstead, self).__init__()
169         self.response = response
170
171
172 def analyse_tags(request, tag_str):
173     try:
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]))
181         raise Http404
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)])))
188
189     try:
190         if len(tags) > settings.MAX_TAG_LIST:
191             raise Http404
192     except AttributeError:
193         pass
194
195     return tags
196
197
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)
203     else:
204         fragments = Fragment.tagged.with_all(fragment_tags)
205
206     if shelf_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)
212
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))
216
217     return object_list(request, fragments, tags=tags, list_type=list_type, extra={
218         'theme_is_set': True,
219         'active_menu_item': 'theme',
220     })
221
222
223 def tagged_object_list(request, tags, list_type):
224     try:
225         tags = analyse_tags(request, tags)
226     except ResponseInstead as e:
227         return e.response
228
229     if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
230         raise Http404
231
232     if any(tag.category in ('theme', 'thing') for tag in tags):
233         return theme_list(request, tags, list_type=list_type)
234
235     if list_type == 'books':
236         books = Book.tagged.with_all(tags)
237
238         if any(tag.category == 'set' for tag in tags):
239             params = {'objects': books}
240         else:
241             books = books.filter(findable=True)
242             params = {
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),
246             }
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()
251         params = {
252             'objects': Book.tagged.with_all(tags, audiobooks),
253             'extra': {
254                 'daisy': Book.tagged.with_all(
255                     tags, audiobooks.filter(media__type='daisy').distinct()
256                 ),
257             }
258         }
259     else:
260         raise Http404
261
262     return object_list(request, tags=tags, list_type=list_type, **params)
263
264
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))
270
271     return render(
272         request,
273         'catalogue/book_fragments.html',
274         {
275             'book': book,
276             'theme': theme,
277             'fragments': fragments,
278             'active_menu_item': 'books',
279         })
280
281
282 @never_cache
283 def book_detail(request, slug):
284     try:
285         book = Book.objects.get(slug=slug)
286     except Book.DoesNotExist:
287         return pdcounter_views.book_stub_detail(request, slug)
288
289     return render(
290         request,
291         'catalogue/2021/book_detail.html' if request.EXPERIMENTS['layout'] == 'new' else 'catalogue/book_detail.html',
292         {
293             'book': book,
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,
298
299             'EXPERIMENTS_SWITCHABLE_layout': True,
300         })
301
302
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'):
307         raise Http404
308
309     audiobooks, projects = book.get_audiobooks()
310
311     return render(
312         request,
313         'catalogue/player.html',
314         {
315             'book': book,
316             'audiobook': '',
317             'audiobooks': audiobooks,
318             'projects': projects,
319         })
320
321
322 def book_text(request, slug):
323     book = get_object_or_404(Book, slug=slug)
324
325     if book.preview and not Membership.is_active_for(request.user):
326         return HttpResponseRedirect(book.get_absolute_url())
327
328     if not book.has_html_file():
329         raise Http404
330     with book.html_file.open('r') as f:
331         book_text = f.read()
332
333     return render(request, 'catalogue/book_text.html', {
334         'book': book,
335         'book_text': book_text,
336         'inserts': DynamicTextInsert.get_all(request)
337     })
338
339
340 # =========
341 # = Admin =
342 # =========
343 @login_required
344 @staff_required
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():
349         try:
350             book_import_form.save()
351         except:
352             import sys
353             import pprint
354             import traceback
355             info = sys.exc_info()
356             exception = pprint.pformat(info[1])
357             tb = '\n'.join(traceback.format_tb(info[2]))
358             return HttpResponse(
359                 _("An error occurred: %(exception)s\n\n%(tb)s") % {
360                     'exception': exception, 'tb': tb
361                 },
362                 content_type='text/plain'
363             )
364         return HttpResponse(_("Book imported successfully"))
365     return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
366
367
368 # info views for API
369
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})
375
376
377 def tag_info(request, tag_id):
378     tag = get_object_or_404(Tag, id=tag_id)
379     return HttpResponse(tag.description)
380
381
382 @never_cache
383 def embargo_link(request, key, format_, slug):
384     book = get_object_or_404(Book, slug=slug)
385     if format_ not in Book.formats:
386         raise Http404
387     if key != book.preview_key:
388         raise Http404
389     media_file = book.get_media(format_)
390     if not book.preview:
391         return HttpResponseRedirect(media_file.url)
392     return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
393
394
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)
401     else:
402         raise Http404('No format specified for zip package')
403     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
404
405
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'
411     honeypot = True
412
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)
417
418     def form_args(self, request, obj):
419         """Override to parse view args and give additional args to the form."""
420         return (obj,), {}
421
422     def validate_object(self, obj, request):
423         book = obj
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)
427
428     def get_object(self, request, slug, *args, **kwargs):
429         book = get_object_or_404(Book, slug=slug)
430         return book
431
432     def context_description(self, request, obj):
433         return obj.pretty_title()
434
435
436 def tag_catalogue(request, category):
437     if category == 'theme':
438         tags = Tag.objects.usage_for_model(
439             Fragment, counts=True).filter(category='theme')
440     else:
441         tags = list(get_top_level_related_tags((), categories=(category,)))
442
443     described_tags = [tag for tag in tags if tag.description]
444
445     if len(described_tags) > 4:
446         best = random.sample(described_tags, 4)
447     else:
448         best = described_tags
449
450     return render(request, 'catalogue/tag_catalogue.html', {
451         'tags': tags,
452         'best': best,
453         'title': constants.CATEGORIES_NAME_PLURAL[category],
454         'whole_category': constants.WHOLE_CATEGORY[category],
455         'active_menu_item': 'theme' if category == 'theme' else None,
456     })
457
458
459 def collections(request):
460     objects = Collection.objects.filter(listed=True)
461
462     if len(objects) > 3:
463         best = random.sample(list(objects), 4)
464     else:
465         best = objects
466
467     return render(request, 'catalogue/collections.html', {
468         'objects': objects,
469         'best': best,
470         'active_menu_item': 'collections'
471     })
472
473
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")
479     cover.save(response)
480     return response
481
482
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))