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
9 from django.conf import settings
10 from django.core.cache import get_cache
11 from django.template import RequestContext
12 from django.template.loader import render_to_string
13 from django.shortcuts import render_to_response, get_object_or_404
14 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
15 from django.core.urlresolvers import reverse
16 from django.db.models import Q
17 from django.contrib.auth.decorators import login_required, user_passes_test
18 from django.utils.http import urlquote_plus
19 from django.utils import translation
20 from django.utils.translation import get_language, ugettext as _, ugettext_lazy
21 from django.views.decorators.vary import vary_on_headers
23 from ajaxable.utils import AjaxableFormView
24 from catalogue import models
25 from catalogue import forms
26 from .helpers import get_related_tags, get_fragment_related_tags, tags_usage_for_books, tags_usage_for_works, tags_usage_for_fragments
27 from catalogue.utils import split_tags, MultiQuerySet, SortedMultiQuerySet
28 from catalogue.templatetags.catalogue_tags import tag_list, collection_list
29 from pdcounter import models as pdcounter_models
30 from pdcounter import views as pdcounter_views
31 from suggest.forms import PublishingSuggestForm
32 from picture.models import Picture, PictureArea
33 from picture.views import picture_list_thumb
35 staff_required = user_passes_test(lambda user: user.is_staff)
36 permanent_cache = get_cache('permanent')
39 @vary_on_headers('X-Requested-With')
40 def catalogue(request):
41 #cache_key = 'catalogue.catalogue/' + get_language()
42 #output = permanent_cache.get(cache_key)
46 common_categories = ('author',)
47 split_categories = ('epoch', 'genre', 'kind')
49 categories = split_tags(tags_usage_for_works(common_categories))
50 book_categories = split_tags(tags_usage_for_books(split_categories))
51 picture_categories = split_tags(
52 models.Tag.objects.usage_for_model(Picture, counts=True).filter(
53 category__in=split_categories))
54 # we want global usage for themes
55 fragment_tags = list(tags_usage_for_fragments(('theme',)))
56 collections = models.Collection.objects.all()
58 render_tag_list = lambda x: render_to_string(
59 'catalogue/tag_list.html', tag_list(x))
61 def render_split(with_books, with_pictures):
64 ctx['books'] = render_tag_list(with_books)
66 ctx['pictures'] = render_tag_list(with_pictures)
67 return render_to_string('catalogue/tag_list_split.html', ctx)
70 output['theme'] = render_tag_list(fragment_tags)
71 for category in common_categories:
72 output[category] = render_tag_list(categories.get(category, []))
73 for category in split_categories:
74 output[category] = render_split(
75 book_categories.get(category, []),
76 picture_categories.get(category, []))
78 output['collections'] = render_to_string(
79 'catalogue/collection_list.html', collection_list(collections))
80 #permanent_cache.set(cache_key, output)
82 return JsonResponse(output)
84 return render_to_response('catalogue/catalogue.html', locals(),
85 context_instance=RequestContext(request))
88 def book_list(request, filter=None, get_filter=None,
89 template_name='catalogue/book_list.html',
90 nav_template_name='catalogue/snippets/book_list_nav.html',
91 list_template_name='catalogue/snippets/book_list.html',
92 cache_key='catalogue.book_list',
95 """ generates a listing of all books, optionally filtered with a test function """
96 cache_key = "%s/%s" % (cache_key, get_language())
97 cached = permanent_cache.get(cache_key)
98 if cached is not None:
99 rendered_nav, rendered_book_list = cached
102 filter = get_filter()
103 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
104 books_nav = OrderedDict()
105 for tag in books_by_author:
106 if books_by_author[tag]:
107 books_nav.setdefault(tag.sort_key[0], []).append(tag)
108 rendered_nav = render_to_string(nav_template_name, locals())
109 rendered_book_list = render_to_string(list_template_name, locals())
110 permanent_cache.set(cache_key, (rendered_nav, rendered_book_list))
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',
119 cache_key='catalogue.audiobook_list')
122 def daisy_list(request):
123 return book_list(request, Q(media__type='daisy'),
124 template_name='catalogue/daisy_list.html',
125 cache_key='catalogue.daisy_list')
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 cache_key='catalogue.collection:%s' % coll.slug,
141 context={'collection': coll})
144 def differentiate_tags(request, tags, ambiguous_slugs):
145 beginning = '/'.join(tag.url_chunk for tag in tags)
146 unparsed = '/'.join(ambiguous_slugs[1:])
148 for tag in models.Tag.objects.filter(slug=ambiguous_slugs[0]):
150 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
153 return render_to_response('catalogue/differentiate_tags.html',
154 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
155 context_instance=RequestContext(request))
158 # TODO: Rewrite this hellish piece of code which tries to do everything
159 def tagged_object_list(request, tags=''):
160 # preliminary tests and conditions
162 tags = models.Tag.get_tag_list(tags)
163 except models.Tag.DoesNotExist:
164 # Perhaps the user is asking about an author in Public Domain
165 # counter (they are not represented in tags)
166 chunks = tags.split('/')
167 if len(chunks) == 2 and chunks[0] == 'autor':
168 return pdcounter_views.author_detail(request, chunks[1])
171 except models.Tag.MultipleObjectsReturned, e:
172 # Ask the user to disambiguate
173 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
174 except models.Tag.UrlDeprecationWarning, e:
175 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
178 if len(tags) > settings.MAX_TAG_LIST:
180 except AttributeError:
183 if len([tag for tag in tags if tag.category == 'book']):
186 # beginning of digestion
187 theme_is_set = [tag for tag in tags if tag.category == 'theme']
188 shelf_is_set = [tag for tag in tags if tag.category == 'set']
189 only_shelf = shelf_is_set and len(tags) == 1
190 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
193 objects = only_author = None
198 shelf_tags = [tag for tag in tags if tag.category == 'set']
199 fragment_tags = [tag for tag in tags if tag.category != 'set']
200 fragments = models.Fragment.tagged.with_all(fragment_tags)
201 areas = PictureArea.tagged.with_all(fragment_tags)
204 # FIXME: book tags here
205 books = models.Book.tagged.with_all(shelf_tags).order_by()
206 l_tags = models.Tag.objects.filter(category='book',
207 slug__in=[book.book_tag_slug() for book in books.iterator()])
208 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
210 related_tags = get_fragment_related_tags(tags)
211 categories = split_tags(related_tags, categories)
212 object_queries.insert(0, fragments)
214 area_keys = [area.pk for area in areas.iterator()]
216 related_tags = PictureArea.tags.usage(counts=True,
217 filters={'pk__in': area_keys})
218 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
220 categories = split_tags(related_tags, categories)
222 # we want the Pictures to go first
223 object_queries.insert(0, areas)
224 objects = MultiQuerySet(*object_queries)
227 books = models.Book.tagged.with_all(tags).order_by(
228 'sort_key_author', 'title')
230 books = models.Book.tagged_top_level(tags).order_by(
231 'sort_key_author', 'title')
233 pictures = Picture.tagged.with_all(tags).order_by(
234 'sort_key_author', 'title')
236 categories = split_tags(get_related_tags(tags))
238 objects = SortedMultiQuerySet(pictures, books,
239 order_by=('sort_key_author', 'title'))
243 only_author = len(tags) == 1 and tags[0].category == 'author'
244 objects = models.Book.objects.none()
246 return render_to_response('catalogue/tagged_object_list.html',
248 'object_list': objects,
249 'categories': categories,
250 'only_shelf': only_shelf,
251 #~ 'only_author': only_author,
252 'only_my_shelf': only_my_shelf,
253 'formats_form': forms.DownloadFormatsForm(),
255 'theme_is_set': theme_is_set,
257 context_instance=RequestContext(request))
260 def book_fragments(request, slug, theme_slug):
261 book = get_object_or_404(models.Book, slug=slug)
262 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
263 fragments = models.Fragment.tagged.with_all([theme]).filter(
264 Q(book=book) | Q(book__ancestor=book))
266 return render_to_response('catalogue/book_fragments.html', locals(),
267 context_instance=RequestContext(request))
270 def book_detail(request, slug):
272 book = models.Book.objects.get(slug=slug)
273 except models.Book.DoesNotExist:
274 return pdcounter_views.book_stub_detail(request, slug)
276 book_children = book.children.all().order_by('parent_number', 'sort_key')
277 return render_to_response('catalogue/book_detail.html', locals(),
278 context_instance=RequestContext(request))
281 def player(request, slug):
282 book = get_object_or_404(models.Book, slug=slug)
283 if not book.has_media('mp3'):
287 for m in book.media.filter(type='ogg').order_by().iterator():
288 ogg_files[m.name] = m
293 for mp3 in book.media.filter(type='mp3').iterator():
294 # ogg files are always from the same project
295 meta = mp3.extra_info
296 project = meta.get('project')
299 project = u'CzytamySłuchając'
301 projects.add((project, meta.get('funded_by', '')))
305 ogg = ogg_files.get(mp3.name)
310 audiobooks.append(media)
312 projects = sorted(projects)
314 extra_info = book.extra_info
316 return render_to_response('catalogue/player.html', locals(),
317 context_instance=RequestContext(request))
320 def book_text(request, slug):
321 book = get_object_or_404(models.Book, slug=slug)
323 if not book.has_html_file():
325 return render_to_response('catalogue/book_text.html', locals(),
326 context_instance=RequestContext(request))
333 def _no_diacritics_regexp(query):
334 """ returns a regexp for searching for a query without diacritics
336 should be locale-aware """
338 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źżŹŻ',
339 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
343 return u"(%s)" % '|'.join(names[l])
344 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
346 def unicode_re_escape(query):
347 """ Unicode-friendly version of re.escape """
348 return re.sub('(?u)(\W)', r'\\\1', query)
350 def _word_starts_with(name, prefix):
351 """returns a Q object getting models having `name` contain a word
352 starting with `prefix`
354 We define word characters as alphanumeric and underscore, like in JS.
356 Works for MySQL, PostgreSQL, Oracle.
357 For SQLite, _sqlite* version is substituted for this.
361 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
362 # can't use [[:<:]] (word start),
363 # but we want both `xy` and `(xy` to catch `(xyz)`
364 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
369 def _word_starts_with_regexp(prefix):
370 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
371 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
374 def _sqlite_word_starts_with(name, prefix):
375 """ version of _word_starts_with for SQLite
377 SQLite in Django uses Python re module
380 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
384 if hasattr(settings, 'DATABASES'):
385 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
386 _word_starts_with = _sqlite_word_starts_with
387 elif settings.DATABASE_ENGINE == 'sqlite3':
388 _word_starts_with = _sqlite_word_starts_with
392 def __init__(self, name, view):
395 self.lower = name.lower()
396 self.category = 'application'
398 return reverse(*self._view)
401 App(u'Leśmianator', (u'lesmianator', )),
405 def _tags_starting_with(prefix, user=None):
406 prefix = prefix.lower()
408 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
409 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
411 books = models.Book.objects.filter(_word_starts_with('title', prefix))
412 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
413 if user and user.is_authenticated():
414 tags = tags.filter(~Q(category='set') | Q(user=user))
416 tags = tags.exclude(category='set')
418 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
419 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
422 def _get_result_link(match, tag_list):
423 if isinstance(match, models.Tag):
424 return reverse('catalogue.views.tagged_object_list',
425 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
427 elif isinstance(match, App):
430 return match.get_absolute_url()
433 def _get_result_type(match):
434 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
437 type = match.category
441 def books_starting_with(prefix):
442 prefix = prefix.lower()
443 return models.Book.objects.filter(_word_starts_with('title', prefix))
446 def find_best_matches(query, user=None):
447 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
450 - zero elements when nothing is found,
451 - one element when a best result is found,
452 - more then one element on multiple exact matches
454 Raises a ValueError on too short a query.
457 query = query.lower()
459 raise ValueError("query must have at least two characters")
461 result = tuple(_tags_starting_with(query, user))
462 # remove pdcounter stuff
463 book_titles = set(match.pretty_title().lower() for match in result
464 if isinstance(match, models.Book))
465 authors = set(match.name.lower() for match in result
466 if isinstance(match, models.Tag) and match.category == 'author')
467 result = tuple(res for res in result if not (
468 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
469 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
472 exact_matches = tuple(res for res in result if res.name.lower() == query)
476 return tuple(result)[:1]
480 tags = request.GET.get('tags', '')
481 prefix = request.GET.get('q', '')
484 tag_list = models.Tag.get_tag_list(tags)
489 result = find_best_matches(prefix, request.user)
491 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
492 context_instance=RequestContext(request))
495 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
496 elif len(result) > 1:
497 return render_to_response('catalogue/search_multiple_hits.html',
498 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
499 context_instance=RequestContext(request))
501 form = PublishingSuggestForm(initial={"books": prefix + ", "})
502 return render_to_response('catalogue/search_no_hits.html',
503 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
504 context_instance=RequestContext(request))
507 def tags_starting_with(request):
508 prefix = request.GET.get('q', '')
509 # Prefix must have at least 2 characters
511 return HttpResponse('')
514 for tag in _tags_starting_with(prefix, request.user):
515 if not tag.name in tags_list:
516 result += "\n" + tag.name
517 tags_list.append(tag.name)
518 return HttpResponse(result)
520 def json_tags_starting_with(request, callback=None):
522 prefix = request.GET.get('q', '')
523 callback = request.GET.get('callback', '')
524 # Prefix must have at least 2 characters
526 return HttpResponse('')
528 for tag in _tags_starting_with(prefix, request.user):
529 if not tag.name in tags_list:
530 tags_list.append(tag.name)
531 if request.GET.get('mozhint', ''):
532 result = [prefix, tags_list]
534 result = {"matches": tags_list}
535 return JsonResponse(result, callback)
543 def import_book(request):
544 """docstring for import_book"""
545 book_import_form = forms.BookImportForm(request.POST, request.FILES)
546 if book_import_form.is_valid():
548 book_import_form.save()
553 info = sys.exc_info()
554 exception = pprint.pformat(info[1])
555 tb = '\n'.join(traceback.format_tb(info[2]))
556 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
557 return HttpResponse(_("Book imported successfully"))
559 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
564 def book_info(request, id, lang='pl'):
565 book = get_object_or_404(models.Book, id=id)
566 # set language by hand
567 translation.activate(lang)
568 return render_to_response('catalogue/book_info.html', locals(),
569 context_instance=RequestContext(request))
572 def tag_info(request, id):
573 tag = get_object_or_404(models.Tag, id=id)
574 return HttpResponse(tag.description)
577 def download_zip(request, format, slug=None):
579 if format in models.Book.ebook_formats:
580 url = models.Book.zip_format(format)
581 elif format in ('mp3', 'ogg') and slug is not None:
582 book = get_object_or_404(models.Book, slug=slug)
583 url = book.zip_audiobooks(format)
585 raise Http404('No format specified for zip package')
586 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
589 class CustomPDFFormView(AjaxableFormView):
590 form_class = forms.CustomPDFForm
591 title = ugettext_lazy('Download custom PDF')
592 submit = ugettext_lazy('Download')
595 def __call__(self, *args, **kwargs):
596 if settings.NO_CUSTOM_PDF:
597 raise Http404('Custom PDF is disabled')
598 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
600 def form_args(self, request, obj):
601 """Override to parse view args and give additional args to the form."""
604 def get_object(self, request, slug, *args, **kwargs):
605 return get_object_or_404(models.Book, slug=slug)
607 def context_description(self, request, obj):
608 return obj.pretty_title()