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.
8 from django.conf import settings
9 from django.core.cache import get_cache
10 from django.template import RequestContext
11 from django.template.loader import render_to_string
12 from django.shortcuts import render_to_response, get_object_or_404, redirect
13 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
14 from django.core.urlresolvers import reverse
15 from django.db.models import Q
16 from django.contrib.auth.decorators import login_required, user_passes_test
17 from django.utils.datastructures import SortedDict
18 from django.utils.http import urlquote_plus
19 from django.utils import translation
20 from django.utils.translation import ugettext as _, ugettext_lazy
21 from django.views.decorators.cache import never_cache
23 from ajaxable.utils import JSONResponse, AjaxableFormView
25 from catalogue import models
26 from catalogue import forms
27 from catalogue.utils import split_tags, MultiQuerySet
28 from catalogue.templatetags.catalogue_tags import tag_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
34 staff_required = user_passes_test(lambda user: user.is_staff)
35 permanent_cache = get_cache('permanent')
38 def catalogue(request):
39 tags = models.Tag.objects.exclude(
40 category__in=('set', 'book')).exclude(book_count=0)
43 tag.count = tag.book_count
44 categories = split_tags(tags)
45 fragment_tags = categories.get('theme', [])
48 render_tag_list = lambda x: render_to_string(
49 'catalogue/tag_list.html', tag_list(x))
50 output = {'theme': render_tag_list(fragment_tags)}
51 for category, tags in categories.items():
52 output[category] = render_tag_list(tags)
53 return JSONResponse(output)
55 return render_to_response('catalogue/catalogue.html', locals(),
56 context_instance=RequestContext(request))
59 def book_list(request, filter=None, template_name='catalogue/book_list.html',
60 nav_template_name='catalogue/snippets/book_list_nav.html',
61 list_template_name='catalogue/snippets/book_list.html',
62 cache_key='catalogue.book_list',
65 """ generates a listing of all books, optionally filtered with a test function """
66 cached = permanent_cache.get(cache_key)
67 if cached is not None:
68 rendered_nav, rendered_book_list = cached
70 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
71 books_nav = SortedDict()
72 for tag in books_by_author:
73 if books_by_author[tag]:
74 books_nav.setdefault(tag.sort_key[0], []).append(tag)
75 rendered_nav = render_to_string(nav_template_name, locals())
76 rendered_book_list = render_to_string(list_template_name, locals())
77 permanent_cache.set(cache_key, (rendered_nav, rendered_book_list))
78 return render_to_response(template_name, locals(),
79 context_instance=RequestContext(request))
82 def audiobook_list(request):
83 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
84 template_name='catalogue/audiobook_list.html',
85 list_template_name='catalogue/snippets/audiobook_list.html',
86 cache_key='catalogue.audiobook_list')
89 def daisy_list(request):
90 return book_list(request, Q(media__type='daisy'),
91 template_name='catalogue/daisy_list.html',
92 cache_key='catalogue.daisy_list')
95 def collection(request, slug):
96 coll = get_object_or_404(models.Collection, slug=slug)
97 slugs = coll.book_slugs.split()
99 slugs = [slug.rstrip('/').rsplit('/', 1)[-1] if '/' in slug else slug
101 return book_list(request, Q(slug__in=slugs),
102 template_name='catalogue/collection.html',
103 cache_key='catalogue.collection:%s' % coll.slug,
104 context={'collection': coll})
107 def differentiate_tags(request, tags, ambiguous_slugs):
108 beginning = '/'.join(tag.url_chunk for tag in tags)
109 unparsed = '/'.join(ambiguous_slugs[1:])
111 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
113 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
116 return render_to_response('catalogue/differentiate_tags.html',
117 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
118 context_instance=RequestContext(request))
122 def tagged_object_list(request, tags=''):
124 tags = models.Tag.get_tag_list(tags)
125 except models.Tag.DoesNotExist:
126 chunks = tags.split('/')
127 if len(chunks) == 2 and chunks[0] == 'autor':
128 return pdcounter_views.author_detail(request, chunks[1])
131 except models.Tag.MultipleObjectsReturned, e:
132 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
133 except models.Tag.UrlDeprecationWarning, e:
134 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
137 if len(tags) > settings.MAX_TAG_LIST:
139 except AttributeError:
142 if len([tag for tag in tags if tag.category == 'book']):
145 theme_is_set = [tag for tag in tags if tag.category == 'theme']
146 shelf_is_set = [tag for tag in tags if tag.category == 'set']
147 only_shelf = shelf_is_set and len(tags) == 1
148 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
150 objects = only_author = None
154 shelf_tags = [tag for tag in tags if tag.category == 'set']
155 fragment_tags = [tag for tag in tags if tag.category != 'set']
156 fragments = models.Fragment.tagged.with_all(fragment_tags)
159 books = models.Book.tagged.with_all(shelf_tags).order_by()
160 l_tags = models.Tag.objects.filter(category='book',
161 slug__in=[book.book_tag_slug() for book in books.iterator()])
162 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
164 # newtagging goes crazy if we just try:
165 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
166 # extra={'where': ["catalogue_tag.category != 'book'"]})
167 fragment_keys = [fragment.pk for fragment in fragments.iterator()]
169 related_tags = models.Fragment.tags.usage(counts=True,
170 filters={'pk__in': fragment_keys},
171 extra={'where': ["catalogue_tag.category != 'book'"]})
172 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
173 categories = split_tags(related_tags)
178 objects = models.Book.tagged.with_all(tags)
180 objects = models.Book.tagged_top_level(tags)
182 # get related tags from `tag_counter` and `theme_counter`
184 tags_pks = [tag.pk for tag in tags]
185 for book in objects.iterator():
186 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
187 if tag_pk in tags_pks:
189 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
190 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
191 related_tags = [tag for tag in related_tags if tag not in tags]
192 for tag in related_tags:
193 tag.count = related_counts[tag.pk]
195 categories = split_tags(related_tags)
199 only_author = len(tags) == 1 and tags[0].category == 'author'
200 objects = models.Book.objects.none()
203 objects = MultiQuerySet(Picture.tagged.with_all(tags), objects)
205 return render_to_response('catalogue/tagged_object_list.html',
207 'object_list': objects,
208 'categories': categories,
209 'only_shelf': only_shelf,
210 'only_author': only_author,
211 'only_my_shelf': only_my_shelf,
212 'formats_form': forms.DownloadFormatsForm(),
214 'theme_is_set': theme_is_set,
216 context_instance=RequestContext(request))
219 def book_fragments(request, slug, theme_slug):
220 book = get_object_or_404(models.Book, slug=slug)
222 book_tag = book.book_tag()
223 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
224 fragments = models.Fragment.tagged.with_all([book_tag, theme])
226 return render_to_response('catalogue/book_fragments.html', locals(),
227 context_instance=RequestContext(request))
231 def book_detail(request, slug):
233 book = models.Book.objects.get(slug=slug)
234 except models.Book.DoesNotExist:
235 return pdcounter_views.book_stub_detail(request, slug)
237 book_children = book.children.all().order_by('parent_number', 'sort_key')
238 return render_to_response('catalogue/book_detail.html', locals(),
239 context_instance=RequestContext(request))
242 def player(request, slug):
243 book = get_object_or_404(models.Book, slug=slug)
244 if not book.has_media('mp3'):
248 for m in book.media.filter(type='ogg').order_by().iterator():
249 ogg_files[m.name] = m
254 for mp3 in book.media.filter(type='mp3').iterator():
255 # ogg files are always from the same project
256 meta = mp3.extra_info
257 project = meta.get('project')
260 project = u'CzytamySłuchając'
262 projects.add((project, meta.get('funded_by', '')))
266 ogg = ogg_files.get(mp3.name)
271 audiobooks.append(media)
273 projects = sorted(projects)
275 extra_info = book.extra_info
277 return render_to_response('catalogue/player.html', locals(),
278 context_instance=RequestContext(request))
281 def book_text(request, slug):
282 book = get_object_or_404(models.Book, slug=slug)
284 if not book.has_html_file():
287 for fragment in book.fragments.all().iterator():
288 for theme in fragment.tags.filter(category='theme').iterator():
289 book_themes.setdefault(theme, []).append(fragment)
291 book_themes = book_themes.items()
292 book_themes.sort(key=lambda s: s[0].sort_key)
293 related = book.related_info()
294 return render_to_response('catalogue/book_text.html', locals(),
295 context_instance=RequestContext(request))
302 def _no_diacritics_regexp(query):
303 """ returns a regexp for searching for a query without diacritics
305 should be locale-aware """
307 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źżŹŻ',
308 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
312 return u"(%s)" % '|'.join(names[l])
313 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
315 def unicode_re_escape(query):
316 """ Unicode-friendly version of re.escape """
317 return re.sub('(?u)(\W)', r'\\\1', query)
319 def _word_starts_with(name, prefix):
320 """returns a Q object getting models having `name` contain a word
321 starting with `prefix`
323 We define word characters as alphanumeric and underscore, like in JS.
325 Works for MySQL, PostgreSQL, Oracle.
326 For SQLite, _sqlite* version is substituted for this.
330 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
331 # can't use [[:<:]] (word start),
332 # but we want both `xy` and `(xy` to catch `(xyz)`
333 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
338 def _word_starts_with_regexp(prefix):
339 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
340 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
343 def _sqlite_word_starts_with(name, prefix):
344 """ version of _word_starts_with for SQLite
346 SQLite in Django uses Python re module
349 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
353 if hasattr(settings, 'DATABASES'):
354 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
355 _word_starts_with = _sqlite_word_starts_with
356 elif settings.DATABASE_ENGINE == 'sqlite3':
357 _word_starts_with = _sqlite_word_starts_with
361 def __init__(self, name, view):
364 self.lower = name.lower()
365 self.category = 'application'
367 return reverse(*self._view)
370 App(u'Leśmianator', (u'lesmianator', )),
374 def _tags_starting_with(prefix, user=None):
375 prefix = prefix.lower()
377 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
378 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
380 books = models.Book.objects.filter(_word_starts_with('title', prefix))
381 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
382 if user and user.is_authenticated():
383 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
385 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
387 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
388 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
391 def _get_result_link(match, tag_list):
392 if isinstance(match, models.Tag):
393 return reverse('catalogue.views.tagged_object_list',
394 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
396 elif isinstance(match, App):
399 return match.get_absolute_url()
402 def _get_result_type(match):
403 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
406 type = match.category
410 def books_starting_with(prefix):
411 prefix = prefix.lower()
412 return models.Book.objects.filter(_word_starts_with('title', prefix))
415 def find_best_matches(query, user=None):
416 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
419 - zero elements when nothing is found,
420 - one element when a best result is found,
421 - more then one element on multiple exact matches
423 Raises a ValueError on too short a query.
426 query = query.lower()
428 raise ValueError("query must have at least two characters")
430 result = tuple(_tags_starting_with(query, user))
431 # remove pdcounter stuff
432 book_titles = set(match.pretty_title().lower() for match in result
433 if isinstance(match, models.Book))
434 authors = set(match.name.lower() for match in result
435 if isinstance(match, models.Tag) and match.category=='author')
436 result = tuple(res for res in result if not (
437 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
438 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
441 exact_matches = tuple(res for res in result if res.name.lower() == query)
445 return tuple(result)[:1]
449 tags = request.GET.get('tags', '')
450 prefix = request.GET.get('q', '')
453 tag_list = models.Tag.get_tag_list(tags)
458 result = find_best_matches(prefix, request.user)
460 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
461 context_instance=RequestContext(request))
464 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
465 elif len(result) > 1:
466 return render_to_response('catalogue/search_multiple_hits.html',
467 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
468 context_instance=RequestContext(request))
470 form = PublishingSuggestForm(initial={"books": prefix + ", "})
471 return render_to_response('catalogue/search_no_hits.html',
472 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
473 context_instance=RequestContext(request))
476 def tags_starting_with(request):
477 prefix = request.GET.get('q', '')
478 # Prefix must have at least 2 characters
480 return HttpResponse('')
483 for tag in _tags_starting_with(prefix, request.user):
484 if not tag.name in tags_list:
485 result += "\n" + tag.name
486 tags_list.append(tag.name)
487 return HttpResponse(result)
489 def json_tags_starting_with(request, callback=None):
491 prefix = request.GET.get('q', '')
492 callback = request.GET.get('callback', '')
493 # Prefix must have at least 2 characters
495 return HttpResponse('')
497 for tag in _tags_starting_with(prefix, request.user):
498 if not tag.name in tags_list:
499 tags_list.append(tag.name)
500 if request.GET.get('mozhint', ''):
501 result = [prefix, tags_list]
503 result = {"matches": tags_list}
504 return JSONResponse(result, callback)
512 def import_book(request):
513 """docstring for import_book"""
514 book_import_form = forms.BookImportForm(request.POST, request.FILES)
515 if book_import_form.is_valid():
517 book_import_form.save()
522 info = sys.exc_info()
523 exception = pprint.pformat(info[1])
524 tb = '\n'.join(traceback.format_tb(info[2]))
525 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
526 return HttpResponse(_("Book imported successfully"))
528 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
533 def book_info(request, id, lang='pl'):
534 book = get_object_or_404(models.Book, id=id)
535 # set language by hand
536 translation.activate(lang)
537 return render_to_response('catalogue/book_info.html', locals(),
538 context_instance=RequestContext(request))
541 def tag_info(request, id):
542 tag = get_object_or_404(models.Tag, id=id)
543 return HttpResponse(tag.description)
546 def download_zip(request, format, slug=None):
548 if format in models.Book.ebook_formats:
549 url = models.Book.zip_format(format)
550 elif format in ('mp3', 'ogg') and slug is not None:
551 book = get_object_or_404(models.Book, slug=slug)
552 url = book.zip_audiobooks(format)
554 raise Http404('No format specified for zip package')
555 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
558 class CustomPDFFormView(AjaxableFormView):
559 form_class = forms.CustomPDFForm
560 title = ugettext_lazy('Download custom PDF')
561 submit = ugettext_lazy('Download')
564 def __call__(self, *args, **kwargs):
565 if settings.NO_CUSTOM_PDF:
566 raise Http404('Custom PDF is disabled')
567 return super(CustomPDFFormView, self).__call__(*args, **kwargs)
569 def form_args(self, request, obj):
570 """Override to parse view args and give additional args to the form."""
573 def get_object(self, request, slug, *args, **kwargs):
574 return get_object_or_404(models.Book, slug=slug)
576 def context_description(self, request, obj):
577 return obj.pretty_title()