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.
5 from collections import OrderedDict
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
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
31 staff_required = user_passes_test(lambda user: user.is_staff)
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',
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,
58 'books_by_parent': books_by_parent,
60 }, context_instance=RequestContext(request))
63 def daisy_list(request):
64 return book_list(request, Q(media__type='daisy'), template_name='catalogue/daisy_list.html')
67 def collection(request, slug):
68 coll = get_object_or_404(Collection, slug=slug)
69 return render(request, 'catalogue/collection.html', {'collection': coll})
72 def differentiate_tags(request, tags, ambiguous_slugs):
73 beginning = '/'.join(tag.url_chunk for tag in tags)
74 unparsed = '/'.join(ambiguous_slugs[1:])
76 for tag in Tag.objects.filter(slug=ambiguous_slugs[0]):
78 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
81 return render_to_response(
82 'catalogue/differentiate_tags.html', {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
83 context_instance=RequestContext(request))
86 def object_list(request, objects, fragments=None, related_tags=None, tags=None, list_type='books', extra=None):
89 tag_ids = [tag.pk for tag in tags]
91 related_tag_lists = []
93 related_tag_lists.append(related_tags)
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')):
99 if list_type == 'gallery':
100 fragments = PictureArea.objects.filter(picture__in=objects)
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')
109 categories = split_tags(*related_tag_lists)
111 objects = list(objects)
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))
118 best = random.sample(objects, 3)
123 'object_list': objects,
124 'categories': categories,
125 'list_type': list_type,
128 'formats_form': forms.DownloadFormatsForm(),
130 'active_menu_item': list_type,
134 return render_to_response(
135 'catalogue/tagged_object_list.html', result,
136 context_instance=RequestContext(request))
139 def literature(request):
140 books = Book.objects.filter(parent=None)
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([]))
147 # 'last_published': last_published,
148 # 'most_popular': most_popular,
152 def gallery(request):
153 return object_list(request, Picture.objects.all(), list_type='gallery')
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(),
163 class ResponseInstead(Exception):
164 def __init__(self, response):
165 super(ResponseInstead, self).__init__()
166 self.response = response
169 def analyse_tags(request, tag_str):
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]))
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)])))
188 if len(tags) > settings.MAX_TAG_LIST:
190 except AttributeError:
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)
202 fragments = Fragment.tagged.with_all(fragment_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))
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))
213 return object_list(request, fragments, tags=tags, list_type=list_type, extra={
214 'theme_is_set': True,
215 'active_menu_item': 'theme',
219 def tagged_object_list(request, tags, list_type):
221 tags = analyse_tags(request, tags)
222 except ResponseInstead as e:
225 if list_type == 'gallery' and any(tag.category == 'set' for tag in tags):
228 if any(tag.category in ('theme', 'thing') for tag in tags):
229 return theme_list(request, tags, list_type=list_type)
231 if list_type == 'books':
232 books = Book.tagged.with_all(tags)
234 if any(tag.category == 'set' for tag in tags):
235 params = {'objects': books}
238 'objects': Book.tagged_top_level(tags),
239 'fragments': Fragment.objects.filter(book__in=books),
240 'related_tags': get_top_level_related_tags(tags),
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()
247 'objects': Book.tagged.with_all(tags, audiobooks),
249 'daisy': Book.tagged.with_all(tags, audiobooks.filter(media__type='daisy').distinct()),
255 return object_list(request, tags=tags, list_type=list_type, **params)
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))
264 return render_to_response('catalogue/book_fragments.html', {
267 'fragments': fragments,
268 'active_menu_item': 'books',
269 }, context_instance=RequestContext(request))
272 def book_detail(request, slug):
274 book = Book.objects.get(slug=slug)
275 except Book.DoesNotExist:
276 return pdcounter_views.book_stub_detail(request, slug)
278 return render_to_response('catalogue/book_detail.html', {
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))
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'):
292 audiobooks, projects = book.get_audiobooks()
294 return render_to_response('catalogue/player.html', {
297 'audiobooks': audiobooks,
298 'projects': projects,
299 }, context_instance=RequestContext(request))
302 def book_text(request, slug):
303 book = get_object_or_404(Book, slug=slug)
305 if not book.has_html_file():
307 return render_to_response('catalogue/book_text.html', {'book': book}, context_instance=RequestContext(request))
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():
320 book_import_form.save()
325 info = sys.exc_info()
326 exception = pprint.pformat(info[1])
327 tb = '\n'.join(traceback.format_tb(info[2]))
329 _("An error occurred: %(exception)s\n\n%(tb)s") % {'exception': exception, 'tb': tb},
330 mimetype='text/plain')
331 return HttpResponse(_("Book imported successfully"))
333 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
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))
345 def tag_info(request, tag_id):
346 tag = get_object_or_404(Tag, id=tag_id)
347 return HttpResponse(tag.description)
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)
357 raise Http404('No format specified for zip package')
358 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
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'
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)
373 def form_args(self, request, obj):
374 """Override to parse view args and give additional args to the form."""
377 def get_object(self, request, slug, *args, **kwargs):
378 return get_object_or_404(Book, slug=slug)
380 def context_description(self, request, obj):
381 return obj.pretty_title()
390 def book_mini(request, pk, with_link=True):
391 # book = get_object_or_404(Book, pk=pk)
393 book = Book.objects.only('cover_thumb', 'title', 'language', 'slug').get(pk=pk)
394 except Book.DoesNotExist:
396 return render(request, 'catalogue/book_mini_box.html', {
398 'no_link': not with_link,
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)
410 return render(request, 'catalogue/book_short.html', {
416 get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
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
426 return render(request, 'catalogue/book_wide.html', {
428 'parents': book.parents(),
429 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
430 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
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'),
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})
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})
451 def tag_box(request, pk):
452 tag = get_object_or_404(Tag, pk=pk)
453 assert tag.category != 'set'
455 return render(request, 'catalogue/tag_box.html', {
461 def collection_box(request, pk):
462 collection = get_object_or_404(Collection, pk=pk)
464 return render(request, 'catalogue/collection_box.html', {
465 'collection': collection,
469 def tag_catalogue(request, category):
470 if category == 'theme':
471 tags = Tag.objects.usage_for_model(
472 Fragment, counts=True).filter(category='theme')
474 tags = list(get_top_level_related_tags((), categories=(category,)))
476 described_tags = [tag for tag in tags if tag.description]
478 if len(described_tags) > 4:
479 best = random.sample(described_tags, 4)
481 best = described_tags
483 return render(request, 'catalogue/tag_catalogue.html', {
486 'title': constants.CATEGORIES_NAME_PLURAL[category],
487 'whole_category': constants.WHOLE_CATEGORY[category],
488 'active_menu_item': 'theme' if category == 'theme' else None,
492 def collections(request):
493 objects = Collection.objects.all()
496 best = random.sample(objects, 3)
500 return render(request, 'catalogue/collections.html', {
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")
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))