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
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
13 from django.core.urlresolvers import reverse
14 from django.db.models import Q
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 models as pdcounter_models
22 from pdcounter import views as pdcounter_views
23 from picture.models import Picture, PictureArea
24 from picture.views import picture_list_thumb
25 from ssify import ssi_included, ssi_expect, SsiVariable as V
26 from suggest.forms import PublishingSuggestForm
27 from catalogue import forms
28 from catalogue.helpers import get_top_level_related_tags
29 from catalogue import models
30 from catalogue.utils import split_tags, MultiQuerySet, SortedMultiQuerySet
31 from catalogue.templatetags.catalogue_tags import tag_list, collection_list
33 staff_required = user_passes_test(lambda user: user.is_staff)
36 def catalogue(request, as_json=False):
37 common_categories = ('author',)
38 split_categories = ('epoch', 'genre', 'kind')
40 categories = split_tags(
41 get_top_level_related_tags(categories=common_categories),
42 models.Tag.objects.usage_for_model(
43 models.Fragment, counts=True).filter(category='theme'),
44 models.Tag.objects.usage_for_model(
45 Picture, counts=True).filter(category__in=common_categories),
46 models.Tag.objects.usage_for_model(
47 PictureArea, counts=True).filter(
50 book_categories = split_tags(
51 get_top_level_related_tags(categories=split_categories)
53 picture_categories = split_tags(
54 models.Tag.objects.usage_for_model(
55 Picture, counts=True).filter(
56 category__in=split_categories),
59 collections = models.Collection.objects.all()
61 def render_tag_list(tags):
62 return render_to_string('catalogue/tag_list.html', tag_list(tags))
64 def render_split(with_books, with_pictures):
67 ctx['books'] = render_tag_list(with_books)
69 ctx['pictures'] = render_tag_list(with_pictures)
70 return render_to_string('catalogue/tag_list_split.html', ctx)
73 output['theme'] = render_tag_list(categories.get('theme', []))
74 for category in common_categories:
75 output[category] = render_tag_list(categories.get(category, []))
76 for category in split_categories:
77 output[category] = render_split(
78 book_categories.get(category, []),
79 picture_categories.get(category, []))
81 output['collections'] = render_to_string(
82 'catalogue/collection_list.html', collection_list(collections))
84 return JsonResponse(output)
86 return render_to_response('catalogue/catalogue.html', locals(),
87 context_instance=RequestContext(request))
91 def catalogue_json(request):
92 return catalogue(request, True)
95 def book_list(request, filter=None, get_filter=None,
96 template_name='catalogue/book_list.html',
97 nav_template_name='catalogue/snippets/book_list_nav.html',
98 list_template_name='catalogue/snippets/book_list.html',
101 """ generates a listing of all books, optionally filtered with a test function """
103 filter = get_filter()
104 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
105 books_nav = OrderedDict()
106 for tag in books_by_author:
107 if books_by_author[tag]:
108 books_nav.setdefault(tag.sort_key[0], []).append(tag)
109 rendered_nav = render_to_string(nav_template_name, locals())
110 rendered_book_list = render_to_string(list_template_name, locals())
111 return render_to_response(template_name, locals(),
112 context_instance=RequestContext(request))
115 def audiobook_list(request):
116 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
117 template_name='catalogue/audiobook_list.html',
118 list_template_name='catalogue/snippets/audiobook_list.html',
122 def daisy_list(request):
123 return book_list(request, Q(media__type='daisy'),
124 template_name='catalogue/daisy_list.html',
128 def collection(request, slug):
129 coll = get_object_or_404(models.Collection, slug=slug)
130 if coll.kind == 'book':
132 tmpl = "catalogue/collection.html"
133 elif coll.kind == 'picture':
134 view = picture_list_thumb
135 tmpl = "picture/collection.html"
137 raise ValueError('How do I show this kind of collection? %s' % coll.kind)
138 return view(request, get_filter=coll.get_query,
140 context={'collection': coll})
143 def differentiate_tags(request, tags, ambiguous_slugs):
144 beginning = '/'.join(tag.url_chunk for tag in tags)
145 unparsed = '/'.join(ambiguous_slugs[1:])
147 for tag in models.Tag.objects.filter(slug=ambiguous_slugs[0]):
149 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
152 return render_to_response('catalogue/differentiate_tags.html',
153 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
154 context_instance=RequestContext(request))
157 # TODO: Rewrite this hellish piece of code which tries to do everything
158 def tagged_object_list(request, tags=''):
159 # preliminary tests and conditions
161 tags = models.Tag.get_tag_list(tags)
162 except models.Tag.DoesNotExist:
163 # Perhaps the user is asking about an author in Public Domain
164 # counter (they are not represented in tags)
165 chunks = tags.split('/')
166 if len(chunks) == 2 and chunks[0] == 'autor':
167 return pdcounter_views.author_detail(request, chunks[1])
170 except models.Tag.MultipleObjectsReturned, e:
171 # Ask the user to disambiguate
172 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
173 except models.Tag.UrlDeprecationWarning, e:
174 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
177 if len(tags) > settings.MAX_TAG_LIST:
179 except AttributeError:
182 # beginning of digestion
183 theme_is_set = [tag for tag in tags if tag.category == 'theme']
184 shelf_is_set = [tag for tag in tags if tag.category == 'set']
185 only_shelf = shelf_is_set and len(tags) == 1
186 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
187 tags_pks = [tag.pk for tag in tags]
192 shelf_tags = [tag for tag in tags if tag.category == 'set']
193 fragment_tags = [tag for tag in tags if tag.category != 'set']
194 fragments = models.Fragment.tagged.with_all(fragment_tags)
195 areas = PictureArea.tagged.with_all(fragment_tags)
198 books = models.Book.tagged.with_all(shelf_tags).order_by()
199 fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
200 areas = PictureArea.objects.none()
202 categories = split_tags(
203 models.Tag.objects.usage_for_queryset(fragments, counts=True
204 ).exclude(pk__in=tags_pks),
205 models.Tag.objects.usage_for_queryset(areas, counts=True
206 ).exclude(pk__in=tags_pks)
209 # we want the Pictures to go first
210 objects = MultiQuerySet(areas, fragments)
212 all_books = models.Book.tagged.with_all(tags)
214 books = all_books.order_by('sort_key_author', 'title')
215 pictures = Picture.objects.none()
216 related_book_tags = models.Tag.objects.usage_for_queryset(
217 books, counts=True).exclude(
218 category='set').exclude(pk__in=tags_pks)
220 books = models.Book.tagged_top_level(tags).order_by(
221 'sort_key_author', 'title')
222 pictures = Picture.tagged.with_all(tags).order_by(
223 'sort_key_author', 'title')
224 related_book_tags = get_top_level_related_tags(tags)
226 fragments = models.Fragment.objects.filter(book__in=all_books)
227 areas = PictureArea.objects.filter(picture__in=pictures)
229 categories = split_tags(
231 models.Tag.objects.usage_for_queryset(
232 pictures, counts=True).exclude(pk__in=tags_pks),
233 models.Tag.objects.usage_for_queryset(
234 fragments, counts=True).filter(
235 category='theme').exclude(pk__in=tags_pks),
236 models.Tag.objects.usage_for_queryset(
237 areas, counts=True).filter(
238 category__in=('theme', 'thing')).exclude(
242 objects = SortedMultiQuerySet(pictures, books,
243 order_by=('sort_key_author', 'title'))
245 return render_to_response('catalogue/tagged_object_list.html',
247 'object_list': objects,
248 'categories': categories,
249 'only_shelf': only_shelf,
250 'only_my_shelf': only_my_shelf,
251 'formats_form': forms.DownloadFormatsForm(),
253 'tags_ids': tags_pks,
254 'theme_is_set': theme_is_set,
256 context_instance=RequestContext(request))
259 def book_fragments(request, slug, theme_slug):
260 book = get_object_or_404(models.Book, slug=slug)
261 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
262 fragments = models.Fragment.tagged.with_all([theme]).filter(
263 Q(book=book) | Q(book__ancestor=book))
265 return render_to_response('catalogue/book_fragments.html', locals(),
266 context_instance=RequestContext(request))
269 def book_detail(request, slug):
271 book = models.Book.objects.get(slug=slug)
272 except models.Book.DoesNotExist:
273 return pdcounter_views.book_stub_detail(request, slug)
275 book_children = book.children.all().order_by('parent_number', 'sort_key')
276 return render_to_response('catalogue/book_detail.html', locals(),
277 context_instance=RequestContext(request))
280 def player(request, slug):
281 book = get_object_or_404(models.Book, slug=slug)
282 if not book.has_media('mp3'):
286 for m in book.media.filter(type='ogg').order_by().iterator():
287 ogg_files[m.name] = m
292 for mp3 in book.media.filter(type='mp3').iterator():
293 # ogg files are always from the same project
294 meta = mp3.extra_info
295 project = meta.get('project')
298 project = u'CzytamySłuchając'
300 projects.add((project, meta.get('funded_by', '')))
304 ogg = ogg_files.get(mp3.name)
309 audiobooks.append(media)
311 projects = sorted(projects)
313 extra_info = book.extra_info
315 return render_to_response('catalogue/player.html', locals(),
316 context_instance=RequestContext(request))
319 def book_text(request, slug):
320 book = get_object_or_404(models.Book, slug=slug)
322 if not book.has_html_file():
324 return render_to_response('catalogue/book_text.html', locals(),
325 context_instance=RequestContext(request))
332 def _no_diacritics_regexp(query):
333 """ returns a regexp for searching for a query without diacritics
335 should be locale-aware """
337 u'a':u'aąĄ', u'c':u'cćĆ', u'e':u'eęĘ', u'l': u'lłŁ', u'n':u'nńŃ', u'o':u'oóÓ', u's':u'sśŚ', u'z':u'zźżŹŻ',
338 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
342 return u"(%s)" % '|'.join(names[l])
343 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
345 def unicode_re_escape(query):
346 """ Unicode-friendly version of re.escape """
347 return re.sub(r'(?u)(\W)', r'\\\1', query)
349 def _word_starts_with(name, prefix):
350 """returns a Q object getting models having `name` contain a word
351 starting with `prefix`
353 We define word characters as alphanumeric and underscore, like in JS.
355 Works for MySQL, PostgreSQL, Oracle.
356 For SQLite, _sqlite* version is substituted for this.
360 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
361 # can't use [[:<:]] (word start),
362 # but we want both `xy` and `(xy` to catch `(xyz)`
363 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
368 def _word_starts_with_regexp(prefix):
369 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
370 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
373 def _sqlite_word_starts_with(name, prefix):
374 """ version of _word_starts_with for SQLite
376 SQLite in Django uses Python re module
379 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
383 if hasattr(settings, 'DATABASES'):
384 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
385 _word_starts_with = _sqlite_word_starts_with
386 elif settings.DATABASE_ENGINE == 'sqlite3':
387 _word_starts_with = _sqlite_word_starts_with
391 def __init__(self, name, view):
394 self.lower = name.lower()
395 self.category = 'application'
397 return reverse(*self._view)
400 App(u'Leśmianator', (u'lesmianator', )),
404 def _tags_starting_with(prefix, user=None):
405 prefix = prefix.lower()
407 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
408 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
410 books = models.Book.objects.filter(_word_starts_with('title', prefix))
411 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
412 if user and user.is_authenticated():
413 tags = tags.filter(~Q(category='set') | Q(user=user))
415 tags = tags.exclude(category='set')
417 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
418 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
421 def _get_result_link(match, tag_list):
422 if isinstance(match, models.Tag):
423 return reverse('catalogue.views.tagged_object_list',
424 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
426 elif isinstance(match, App):
429 return match.get_absolute_url()
432 def _get_result_type(match):
433 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
436 match_type = match.category
440 def books_starting_with(prefix):
441 prefix = prefix.lower()
442 return models.Book.objects.filter(_word_starts_with('title', prefix))
445 def find_best_matches(query, user=None):
446 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
449 - zero elements when nothing is found,
450 - one element when a best result is found,
451 - more then one element on multiple exact matches
453 Raises a ValueError on too short a query.
456 query = query.lower()
458 raise ValueError("query must have at least two characters")
460 result = tuple(_tags_starting_with(query, user))
461 # remove pdcounter stuff
462 book_titles = set(match.pretty_title().lower() for match in result
463 if isinstance(match, models.Book))
464 authors = set(match.name.lower() for match in result
465 if isinstance(match, models.Tag) and match.category == 'author')
466 result = tuple(res for res in result if not (
467 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
468 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
471 exact_matches = tuple(res for res in result if res.name.lower() == query)
475 return tuple(result)[:1]
479 tags = request.GET.get('tags', '')
480 prefix = request.GET.get('q', '')
483 tag_list = models.Tag.get_tag_list(tags)
488 result = find_best_matches(prefix, request.user)
490 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
491 context_instance=RequestContext(request))
494 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
495 elif len(result) > 1:
496 return render_to_response('catalogue/search_multiple_hits.html',
497 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
498 context_instance=RequestContext(request))
500 form = PublishingSuggestForm(initial={"books": prefix + ", "})
501 return render_to_response('catalogue/search_no_hits.html',
502 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
503 context_instance=RequestContext(request))
506 def tags_starting_with(request):
507 prefix = request.GET.get('q', '')
508 # Prefix must have at least 2 characters
510 return HttpResponse('')
513 for tag in _tags_starting_with(prefix, request.user):
514 if not tag.name in tags_list:
515 result += "\n" + tag.name
516 tags_list.append(tag.name)
517 return HttpResponse(result)
519 def json_tags_starting_with(request, callback=None):
521 prefix = request.GET.get('q', '')
522 callback = request.GET.get('callback', '')
523 # Prefix must have at least 2 characters
525 return HttpResponse('')
527 for tag in _tags_starting_with(prefix, request.user):
528 if not tag.name in tags_list:
529 tags_list.append(tag.name)
530 if request.GET.get('mozhint', ''):
531 result = [prefix, tags_list]
533 result = {"matches": tags_list}
534 response = JsonResponse(result, safe=False)
536 response.content = callback + "(" + response.content + ");"
545 def import_book(request):
546 """docstring for import_book"""
547 book_import_form = forms.BookImportForm(request.POST, request.FILES)
548 if book_import_form.is_valid():
550 book_import_form.save()
555 info = sys.exc_info()
556 exception = pprint.pformat(info[1])
557 tb = '\n'.join(traceback.format_tb(info[2]))
558 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
559 return HttpResponse(_("Book imported successfully"))
561 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
566 def book_info(request, id, lang='pl'):
567 book = get_object_or_404(models.Book, id=id)
568 # set language by hand
569 translation.activate(lang)
570 return render_to_response('catalogue/book_info.html', locals(),
571 context_instance=RequestContext(request))
574 def tag_info(request, id):
575 tag = get_object_or_404(models.Tag, id=id)
576 return HttpResponse(tag.description)
579 def download_zip(request, format, slug=None):
581 if format in models.Book.ebook_formats:
582 url = models.Book.zip_format(format)
583 elif format in ('mp3', 'ogg') and slug is not None:
584 book = get_object_or_404(models.Book, slug=slug)
585 url = book.zip_audiobooks(format)
587 raise Http404('No format specified for zip package')
588 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
591 class CustomPDFFormView(AjaxableFormView):
592 form_class = forms.CustomPDFForm
593 title = ugettext_lazy('Download custom PDF')
594 submit = ugettext_lazy('Download')
597 def __call__(self, *args, **kwargs):
598 if settings.NO_CUSTOM_PDF:
599 raise Http404('Custom PDF is disabled')
600 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
602 def form_args(self, request, obj):
603 """Override to parse view args and give additional args to the form."""
606 def get_object(self, request, slug, *args, **kwargs):
607 return get_object_or_404(models.Book, slug=slug)
609 def context_description(self, request, obj):
610 return obj.pretty_title()
619 def book_mini(request, pk, with_link=True):
620 book = get_object_or_404(models.Book, pk=pk)
621 author_str = ", ".join(tag.name
622 for tag in book.tags.filter(category='author'))
623 return render(request, 'catalogue/book_mini_box.html', {
625 'author_str': author_str,
626 'with_link': with_link,
627 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
631 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
632 ('ssify.get_csrf_token',),
633 ('social_tags.likes_book', (ipk,)),
634 ('social_tags.book_shelf_tags', (ipk,)),
635 ))(ssi_expect(pk, int)))
636 def book_short(request, pk):
637 book = get_object_or_404(models.Book, pk=pk)
638 stage_note, stage_note_url = book.stage_note()
640 return render(request, 'catalogue/book_short.html', {
642 'has_audio': book.has_media('mp3'),
643 'main_link': book.get_absolute_url(),
644 'parents': book.parents(),
645 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
646 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
647 'stage_note': stage_note,
648 'stage_note_url': stage_note_url,
652 @ssi_included(get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
654 ('social_tags.choose_cite', [ipk]),
655 ('catalogue_tags.choose_fragment', [ipk], {
656 'unless': V('social_tags.choose_cite', [ipk])}),
657 ))(ssi_expect(pk, int)))
658 def book_wide(request, pk):
659 book = get_object_or_404(models.Book, pk=pk)
660 stage_note, stage_note_url = book.stage_note()
661 extra_info = book.extra_info
663 return render(request, 'catalogue/book_wide.html', {
665 'has_audio': book.has_media('mp3'),
666 'parents': book.parents(),
667 'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
668 'show_lang': book.language_code() != settings.LANGUAGE_CODE,
669 'stage_note': stage_note,
670 'stage_note_url': stage_note_url,
672 'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
673 'extra_info': extra_info,
674 'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
675 'themes': book.related_themes(),
680 def fragment_short(request, pk):
681 fragment = get_object_or_404(models.Fragment, pk=pk)
682 return render(request, 'catalogue/fragment_short.html',
683 {'fragment': fragment})
687 def fragment_promo(request, pk):
688 fragment = get_object_or_404(models.Fragment, pk=pk)
689 return render(request, 'catalogue/fragment_promo.html', {