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