904cdc531324cb06baaeda5dc030d3ab67fc8016
[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', {'collection': coll})
70
71
72 def differentiate_tags(request, tags, ambiguous_slugs):
73     beginning = '/'.join(tag.url_chunk for tag in tags)
74     unparsed = '/'.join(ambiguous_slugs[1:])
75     options = []
76     for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
77         options.append({
78             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
79             'tags': [tag]
80         })
81     return render(
82         request,
83         'catalogue/differentiate_tags.html',
84         {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]}
85     )
86
87
88 def object_list(request, objects, fragments=None, related_tags=None, tags=None,
89                 list_type='books', extra=None):
90     if not tags:
91         tags = []
92     tag_ids = [tag.pk for tag in tags]
93
94     related_tag_lists = []
95     if related_tags:
96         related_tag_lists.append(related_tags)
97     else:
98         related_tag_lists.append(
99             Tag.objects.usage_for_queryset(
100                 objects, counts=True
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)
106             else:
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')
115
116     categories = split_tags(*related_tag_lists)
117
118     objects = list(objects)
119
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))
123
124     if len(objects) > 3:
125         best = random.sample(objects, 3)
126     else:
127         best = objects
128
129     result = {
130         'object_list': objects,
131         'categories': categories,
132         'list_type': list_type,
133         'tags': tags,
134
135         'formats_form': forms.DownloadFormatsForm(),
136         'best': best,
137         'active_menu_item': list_type,
138     }
139     if extra:
140         result.update(extra)
141     return render(
142         request,
143         'catalogue/tagged_object_list.html', result,
144     )
145
146
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([]))
150
151
152 def gallery(request):
153     return object_list(request, Picture.objects.all(), list_type='gallery')
154
155
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(),
160     })
161
162
163 class ResponseInstead(Exception):
164     def __init__(self, response):
165         super(ResponseInstead, self).__init__()
166         self.response = response
167
168
169 def analyse_tags(request, tag_str):
170     try:
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]))
178         raise Http404
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)])))
185
186     try:
187         if len(tags) > settings.MAX_TAG_LIST:
188             raise Http404
189     except AttributeError:
190         pass
191
192     return tags
193
194
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)
200     else:
201         fragments = Fragment.tagged.with_all(fragment_tags)
202
203     if shelf_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)
209
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))
213
214     return object_list(request, fragments, tags=tags, list_type=list_type, extra={
215         'theme_is_set': True,
216         'active_menu_item': 'theme',
217     })
218
219
220 def tagged_object_list(request, tags, list_type):
221     try:
222         tags = analyse_tags(request, tags)
223     except ResponseInstead as e:
224         return e.response
225
226     if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
227         raise Http404
228
229     if any(tag.category in ('theme', 'thing') for tag in tags):
230         return theme_list(request, tags, list_type=list_type)
231
232     if list_type == 'books':
233         books = Book.tagged.with_all(tags)
234
235         if any(tag.category == 'set' for tag in tags):
236             params = {'objects': books}
237         else:
238             books = books.filter(findable=True)
239             params = {
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),
243             }
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()
248         params = {
249             'objects': Book.tagged.with_all(tags, audiobooks),
250             'extra': {
251                 'daisy': Book.tagged.with_all(
252                     tags, audiobooks.filter(media__type='daisy').distinct()
253                 ),
254             }
255         }
256     else:
257         raise Http404
258
259     return object_list(request, tags=tags, list_type=list_type, **params)
260
261
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))
267
268     return render(
269         request,
270         'catalogue/book_fragments.html',
271         {
272             'book': book,
273             'theme': theme,
274             'fragments': fragments,
275             'active_menu_item': 'books',
276         })
277
278
279 @never_cache
280 def book_detail(request, slug):
281     try:
282         book = Book.objects.get(slug=slug)
283     except Book.DoesNotExist:
284         return pdcounter_views.book_stub_detail(request, slug)
285
286     return render(
287         request,
288         'catalogue/book_detail.html',
289         {
290             'book': book,
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,
295         })
296
297
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'):
302         raise Http404
303
304     audiobooks, projects = book.get_audiobooks()
305
306     return render(
307         request,
308         'catalogue/player.html',
309         {
310             'book': book,
311             'audiobook': '',
312             'audiobooks': audiobooks,
313             'projects': projects,
314         })
315
316
317 def book_text(request, slug):
318     book = get_object_or_404(Book, slug=slug)
319
320     if book.preview and not Membership.is_active_for(request.user):
321         return HttpResponseRedirect(book.get_absolute_url())
322
323     if not book.has_html_file():
324         raise Http404
325     with book.html_file.open('r') as f:
326         book_text = f.read()
327
328     return render(request, 'catalogue/book_text.html', {
329         'book': book,
330         'book_text': book_text,
331         'inserts': DynamicTextInsert.get_all(request)
332     })
333
334
335 # =========
336 # = Admin =
337 # =========
338 @login_required
339 @staff_required
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():
344         try:
345             book_import_form.save()
346         except:
347             import sys
348             import pprint
349             import traceback
350             info = sys.exc_info()
351             exception = pprint.pformat(info[1])
352             tb = '\n'.join(traceback.format_tb(info[2]))
353             return HttpResponse(
354                 _("An error occurred: %(exception)s\n\n%(tb)s") % {
355                     'exception': exception, 'tb': tb
356                 },
357                 content_type='text/plain'
358             )
359         return HttpResponse(_("Book imported successfully"))
360     return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
361
362
363 # info views for API
364
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})
370
371
372 def tag_info(request, tag_id):
373     tag = get_object_or_404(Tag, id=tag_id)
374     return HttpResponse(tag.description)
375
376
377 @never_cache
378 def embargo_link(request, key, format_, slug):
379     book = get_object_or_404(Book, slug=slug)
380     if format_ not in Book.formats:
381         raise Http404
382     if key != book.preview_key:
383         raise Http404
384     media_file = book.get_media(format_)
385     if not book.preview:
386         return HttpResponseRedirect(media_file.url)
387     return HttpResponse(media_file, content_type=constants.EBOOK_CONTENT_TYPES[format_])
388
389
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)
396     else:
397         raise Http404('No format specified for zip package')
398     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
399
400
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'
406     honeypot = True
407
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)
412
413     def form_args(self, request, obj):
414         """Override to parse view args and give additional args to the form."""
415         return (obj,), {}
416
417     def validate_object(self, obj, request):
418         book = obj
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)
422
423     def get_object(self, request, slug, *args, **kwargs):
424         book = get_object_or_404(Book, slug=slug)
425         return book
426
427     def context_description(self, request, obj):
428         return obj.pretty_title()
429
430
431 def tag_catalogue(request, category):
432     if category == 'theme':
433         tags = Tag.objects.usage_for_model(
434             Fragment, counts=True).filter(category='theme')
435     else:
436         tags = list(get_top_level_related_tags((), categories=(category,)))
437
438     described_tags = [tag for tag in tags if tag.description]
439
440     if len(described_tags) > 4:
441         best = random.sample(described_tags, 4)
442     else:
443         best = described_tags
444
445     return render(request, 'catalogue/tag_catalogue.html', {
446         'tags': tags,
447         'best': best,
448         'title': constants.CATEGORIES_NAME_PLURAL[category],
449         'whole_category': constants.WHOLE_CATEGORY[category],
450         'active_menu_item': 'theme' if category == 'theme' else None,
451     })
452
453
454 def collections(request):
455     objects = Collection.objects.filter(listed=True)
456
457     if len(objects) > 3:
458         best = random.sample(list(objects), 3)
459     else:
460         best = objects
461
462     return render(request, 'catalogue/collections.html', {
463         'objects': objects,
464         'best': best,
465     })
466
467
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")
473     cover.save(response)
474     return response
475
476
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))