skip fragments with no theme hit
[wolnelektury.git] / src / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from collections import OrderedDict
6 import random
7
8 from django.conf import settings
9 from django.template import RequestContext
10 from django.template.loader import render_to_string
11 from django.shortcuts import render_to_response, get_object_or_404, render, redirect
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
13 from django.core.urlresolvers 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.http import urlquote_plus
17 from django.utils import translation
18 from django.utils.translation import ugettext as _, ugettext_lazy
19
20 from ajaxable.utils import AjaxableFormView
21 from pdcounter import views as pdcounter_views
22 from picture.models import Picture, PictureArea
23 from ssify import ssi_included, ssi_expect, SsiVariable as Var
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(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     # WTF: dlaczego nie include?
53     return render_to_response(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     }, context_instance=RequestContext(request))
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_to_response(
82         'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
83         context_instance=RequestContext(request))
84
85
86 def object_list(request, objects, fragments=None, related_tags=None, tags=None, list_type='books', extra=None):
87     if not tags:
88         tags = []
89     tag_ids = [tag.pk for tag in tags]
90
91     related_tag_lists = []
92     if related_tags:
93         related_tag_lists.append(related_tags)
94     else:
95         related_tag_lists.append(
96             Tag.objects.usage_for_queryset(objects, counts=True).exclude(category='set').exclude(pk__in=tag_ids))
97     if not (extra and extra.get('theme_is_set')):
98         if fragments is None:
99             if list_type == 'gallery':
100                 fragments = PictureArea.objects.filter(picture__in=objects)
101             else:
102                 fragments = Fragment.objects.filter(book__in=objects)
103         related_tag_lists.append(
104             Tag.objects.usage_for_queryset(fragments, counts=True).filter(category='theme').exclude(pk__in=tag_ids)
105             .only('name', 'sort_key', 'category', 'slug'))
106         if isinstance(objects, QuerySet):
107             objects = prefetch_relations(objects, 'author')
108
109     categories = split_tags(*related_tag_lists)
110
111     objects = list(objects)
112
113     if not objects and len(tags) == 1 and list_type == 'books':
114         if PictureArea.tagged.with_any(tags).exists() or Picture.tagged.with_any(tags).exists():
115             return redirect('tagged_object_list_gallery', '/'.join(tag.url_chunk for tag in tags))
116
117     if len(objects) > 3:
118         best = random.sample(objects, 3)
119     else:
120         best = objects
121
122     result = {
123         'object_list': objects,
124         'categories': categories,
125         'list_type': list_type,
126         'tags': tags,
127
128         'formats_form': forms.DownloadFormatsForm(),
129         'best': best,
130         'active_menu_item': list_type,
131     }
132     if extra:
133         result.update(extra)
134     return render_to_response(
135         'catalogue/tagged_object_list.html', result,
136         context_instance=RequestContext(request))
137
138
139 def literature(request):
140     books = Book.objects.filter(parent=None)
141
142     # last_published = Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:20]
143     # most_popular = Book.objects.exclude(cover_thumb='')\
144     #                    .order_by('-popularity__count', 'sort_key_author', 'sort_key')[:20]
145     return object_list(request, books, related_tags=get_top_level_related_tags([]))
146     # extra={
147     #     'last_published': last_published,
148     #     'most_popular': most_popular,
149     # })
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(media__type__in=('mp3', 'ogg')).distinct()
158     return object_list(request, audiobooks, list_type='audiobooks', extra={
159         'daisy': Book.objects.filter(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         else:
179             raise Http404
180     except Tag.MultipleObjectsReturned, e:
181         # Ask the user to disambiguate
182         raise ResponseInstead(differentiate_tags(request, e.tags, e.ambiguous_slugs))
183     except Tag.UrlDeprecationWarning, e:
184         raise ResponseInstead(HttpResponsePermanentRedirect(
185             reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)])))
186
187     try:
188         if len(tags) > settings.MAX_TAG_LIST:
189             raise Http404
190     except AttributeError:
191         pass
192
193     return tags
194
195
196 def theme_list(request, tags, list_type):
197     shelf_tags = [tag for tag in tags if tag.category == 'set']
198     fragment_tags = [tag for tag in tags if tag.category != 'set']
199     if list_type == 'gallery':
200         fragments = PictureArea.tagged.with_all(fragment_tags)
201     else:
202         fragments = Fragment.tagged.with_all(fragment_tags)
203
204     if shelf_tags:
205         # TODO: Pictures on shelves not supported yet.
206         books = Book.tagged.with_all(shelf_tags).order_by()
207         fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
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             params = {
238                 'objects': Book.tagged_top_level(tags),
239                 'fragments': Fragment.objects.filter(book__in=books),
240                 'related_tags': get_top_level_related_tags(tags),
241             }
242     elif list_type == 'gallery':
243         params = {'objects': Picture.tagged.with_all(tags)}
244     elif list_type == 'audiobooks':
245         audiobooks = Book.objects.filter(media__type__in=('mp3', 'ogg')).distinct()
246         params = {
247             'objects': Book.tagged.with_all(tags, audiobooks),
248             'extra': {
249                 'daisy': Book.tagged.with_all(tags, audiobooks.filter(media__type='daisy').distinct()),
250             }
251         }
252     else:
253         raise Http404
254
255     return object_list(request, tags=tags, list_type=list_type, **params)
256
257
258 def book_fragments(request, slug, theme_slug):
259     book = get_object_or_404(Book, slug=slug)
260     theme = get_object_or_404(Tag, slug=theme_slug, category='theme')
261     fragments = Fragment.tagged.with_all([theme]).filter(
262         Q(book=book) | Q(book__ancestor=book))
263
264     return render_to_response('catalogue/book_fragments.html', {
265         'book': book,
266         'theme': theme,
267         'fragments': fragments,
268         'active_menu_item': 'books',
269     }, context_instance=RequestContext(request))
270
271
272 def book_detail(request, slug):
273     try:
274         book = Book.objects.get(slug=slug)
275     except Book.DoesNotExist:
276         return pdcounter_views.book_stub_detail(request, slug)
277
278     return render_to_response('catalogue/book_detail.html', {
279         'book': book,
280         'tags': book.tags.exclude(category__in=('set', 'theme')),
281         'book_children': book.children.all().order_by('parent_number', 'sort_key'),
282         'active_menu_item': 'books',
283     }, context_instance=RequestContext(request))
284
285
286 # używane w publicznym interfejsie
287 def player(request, slug):
288     book = get_object_or_404(Book, slug=slug)
289     if not book.has_media('mp3'):
290         raise Http404
291
292     audiobooks, projects = book.get_audiobooks()
293
294     return render_to_response('catalogue/player.html', {
295         'book': book,
296         'audiobook': '',
297         'audiobooks': audiobooks,
298         'projects': projects,
299     }, context_instance=RequestContext(request))
300
301
302 def book_text(request, slug):
303     book = get_object_or_404(Book, slug=slug)
304
305     if not book.has_html_file():
306         raise Http404
307     return render_to_response('catalogue/book_text.html', {'book': book}, context_instance=RequestContext(request))
308
309
310 # =========
311 # = Admin =
312 # =========
313 @login_required
314 @staff_required
315 def import_book(request):
316     """docstring for import_book"""
317     book_import_form = forms.BookImportForm(request.POST, request.FILES)
318     if book_import_form.is_valid():
319         try:
320             book_import_form.save()
321         except:
322             import sys
323             import pprint
324             import traceback
325             info = sys.exc_info()
326             exception = pprint.pformat(info[1])
327             tb = '\n'.join(traceback.format_tb(info[2]))
328             return HttpResponse(
329                     _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
330                     mimetype='text/plain')
331         return HttpResponse(_("Book imported successfully"))
332     else:
333         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
334
335
336 # info views for API
337
338 def book_info(request, book_id, lang='pl'):
339     book = get_object_or_404(Book, id=book_id)
340     # set language by hand
341     translation.activate(lang)
342     return render_to_response('catalogue/book_info.html', {'book': book}, context_instance=RequestContext(request))
343
344
345 def tag_info(request, tag_id):
346     tag = get_object_or_404(Tag, id=tag_id)
347     return HttpResponse(tag.description)
348
349
350 def download_zip(request, format, slug=None):
351     if format in Book.ebook_formats:
352         url = Book.zip_format(format)
353     elif format in ('mp3', 'ogg') and slug is not None:
354         book = get_object_or_404(Book, slug=slug)
355         url = book.zip_audiobooks(format)
356     else:
357         raise Http404('No format specified for zip package')
358     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
359
360
361 class CustomPDFFormView(AjaxableFormView):
362     form_class = forms.CustomPDFForm
363     title = ugettext_lazy('Download custom PDF')
364     submit = ugettext_lazy('Download')
365     template = 'catalogue/custom_pdf_form.html'
366     honeypot = True
367
368     def __call__(self, *args, **kwargs):
369         if settings.NO_CUSTOM_PDF:
370             raise Http404('Custom PDF is disabled')
371         return super(CustomPDFFormView, self).__call__(*args, **kwargs)
372
373     def form_args(self, request, obj):
374         """Override to parse view args and give additional args to the form."""
375         return (obj,), {}
376
377     def get_object(self, request, slug, *args, **kwargs):
378         return get_object_or_404(Book, slug=slug)
379
380     def context_description(self, request, obj):
381         return obj.pretty_title()
382
383
384 ####
385 # Includes
386 ####
387
388
389 @ssi_included
390 def book_mini(request, pk, with_link=True):
391     # book = get_object_or_404(Book, pk=pk)
392     try:
393         book = Book.objects.only('cover_thumb', 'title', 'language', 'slug').get(pk=pk)
394     except Book.DoesNotExist:
395         raise Http404
396     return render(request, 'catalogue/book_mini_box.html', {
397         'book': book,
398         'no_link': not with_link,
399     })
400
401
402 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
403         ('ssify.get_csrf_token',),
404         ('social_tags.likes_book', (ipk,)),
405         ('social_tags.book_shelf_tags', (ipk,)),
406     ))(ssi_expect(pk, int)))
407 def book_short(request, pk):
408     book = get_object_or_404(Book, pk=pk)
409
410     return render(request, 'catalogue/book_short.html', {
411         'book': book,
412     })
413
414
415 @ssi_included(
416     get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
417     (lambda ipk: (
418         ('social_tags.choose_cite', [ipk]),
419         ('catalogue_tags.choose_fragment', [ipk], {
420             'unless': Var('social_tags.choose_cite', [ipk])}),
421     ))(ssi_expect(pk, int)))
422 def book_wide(request, pk):
423     book = get_object_or_404(Book, pk=pk)
424     extra_info = book.extra_info
425
426     return render(request, 'catalogue/book_wide.html', {
427         'book': book,
428         'parents': book.parents(),
429         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
430         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
431
432         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
433         'extra_info': extra_info,
434         'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
435     })
436
437
438 @ssi_included
439 def fragment_short(request, pk):
440     fragment = get_object_or_404(Fragment, pk=pk)
441     return render(request, 'catalogue/fragment_short.html', {'fragment': fragment})
442
443
444 @ssi_included
445 def fragment_promo(request, pk):
446     fragment = get_object_or_404(Fragment, pk=pk)
447     return render(request, 'catalogue/fragment_promo.html', {'fragment': fragment})
448
449
450 @ssi_included
451 def tag_box(request, pk):
452     tag = get_object_or_404(Tag, pk=pk)
453     assert tag.category != 'set'
454
455     return render(request, 'catalogue/tag_box.html', {
456         'tag': tag,
457     })
458
459
460 @ssi_included
461 def collection_box(request, pk):
462     collection = get_object_or_404(Collection, pk=pk)
463
464     return render(request, 'catalogue/collection_box.html', {
465         'collection': collection,
466     })
467
468
469 def tag_catalogue(request, category):
470     if category == 'theme':
471         tags = Tag.objects.usage_for_model(
472             Fragment, counts=True).filter(category='theme')
473     else:
474         tags = list(get_top_level_related_tags((), categories=(category,)))
475
476     described_tags = [tag for tag in tags if tag.description]
477
478     if len(described_tags) > 4:
479         best = random.sample(described_tags, 4)
480     else:
481         best = described_tags
482
483     return render(request, 'catalogue/tag_catalogue.html', {
484         'tags': tags,
485         'best': best,
486         'title': constants.CATEGORIES_NAME_PLURAL[category],
487         'whole_category': constants.WHOLE_CATEGORY[category],
488         'active_menu_item': 'theme' if category == 'theme' else None,
489     })
490
491
492 def collections(request):
493     objects = Collection.objects.all()
494
495     if len(objects) > 3:
496         best = random.sample(objects, 3)
497     else:
498         best = objects
499
500     return render(request, 'catalogue/collections.html', {
501         'objects': objects,
502         'best': best,
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.extra_info.get('isbn_%s' % book_format))