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.
7 from datetime import datetime
9 from django.conf import settings
10 from django.template import RequestContext
11 from django.shortcuts import render_to_response, get_object_or_404
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
13 from django.core.urlresolvers import reverse
14 from django.db.models import Count, Sum, Q
15 from django.contrib.auth.decorators import login_required, user_passes_test
16 from django.utils.datastructures import SortedDict
17 from django.views.decorators.http import require_POST
18 from django.contrib import auth
19 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
20 from django.utils.http import urlquote_plus
21 from django.views.decorators import cache
22 from django.utils import translation
23 from django.utils.translation import ugettext as _
24 from django.views.generic.list_detail import object_list
26 from ajaxable.utils import LazyEncoder, JSONResponse
27 from catalogue import models
28 from catalogue import forms
29 from catalogue.utils import (split_tags, AttachmentHttpResponse,
30 async_build_pdf, MultiQuerySet)
31 from catalogue.tasks import touch_tag
32 from pdcounter import models as pdcounter_models
33 from pdcounter import views as pdcounter_views
34 from suggest.forms import PublishingSuggestForm
35 from picture.models import Picture
39 staff_required = user_passes_test(lambda user: user.is_staff)
42 def catalogue(request):
43 tags = models.Tag.objects.exclude(
44 category__in=('set', 'book')).exclude(book_count=0)
47 tag.count = tag.book_count
48 categories = split_tags(tags)
49 fragment_tags = categories.get('theme', [])
51 return render_to_response('catalogue/catalogue.html', locals(),
52 context_instance=RequestContext(request))
55 def book_list(request, filter=None, template_name='catalogue/book_list.html'):
56 """ generates a listing of all books, optionally filtered with a test function """
58 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
59 books_nav = SortedDict()
60 for tag in books_by_author:
61 if books_by_author[tag]:
62 books_nav.setdefault(tag.sort_key[0], []).append(tag)
64 return render_to_response(template_name, locals(),
65 context_instance=RequestContext(request))
68 def audiobook_list(request):
69 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
70 template_name='catalogue/audiobook_list.html')
73 def daisy_list(request):
74 return book_list(request, Q(media__type='daisy'),
75 template_name='catalogue/daisy_list.html')
78 def differentiate_tags(request, tags, ambiguous_slugs):
79 beginning = '/'.join(tag.url_chunk for tag in tags)
80 unparsed = '/'.join(ambiguous_slugs[1:])
82 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
84 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
87 return render_to_response('catalogue/differentiate_tags.html',
88 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
89 context_instance=RequestContext(request))
92 def tagged_object_list(request, tags=''):
93 # import pdb; pdb.set_trace()
95 tags = models.Tag.get_tag_list(tags)
96 except models.Tag.DoesNotExist:
97 chunks = tags.split('/')
98 if len(chunks) == 2 and chunks[0] == 'autor':
99 return pdcounter_views.author_detail(request, chunks[1])
102 except models.Tag.MultipleObjectsReturned, e:
103 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
104 except models.Tag.UrlDeprecationWarning, e:
105 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
108 if len(tags) > settings.MAX_TAG_LIST:
110 except AttributeError:
113 if len([tag for tag in tags if tag.category == 'book']):
116 theme_is_set = [tag for tag in tags if tag.category == 'theme']
117 shelf_is_set = [tag for tag in tags if tag.category == 'set']
118 only_shelf = shelf_is_set and len(tags) == 1
119 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
121 objects = only_author = None
125 shelf_tags = [tag for tag in tags if tag.category == 'set']
126 fragment_tags = [tag for tag in tags if tag.category != 'set']
127 fragments = models.Fragment.tagged.with_all(fragment_tags)
130 books = models.Book.tagged.with_all(shelf_tags).order_by()
131 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
132 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
134 # newtagging goes crazy if we just try:
135 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
136 # extra={'where': ["catalogue_tag.category != 'book'"]})
137 fragment_keys = [fragment.pk for fragment in fragments]
139 related_tags = models.Fragment.tags.usage(counts=True,
140 filters={'pk__in': fragment_keys},
141 extra={'where': ["catalogue_tag.category != 'book'"]})
142 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
143 categories = split_tags(related_tags)
148 objects = models.Book.tagged.with_all(tags)
150 objects = models.Book.tagged_top_level(tags)
152 # get related tags from `tag_counter` and `theme_counter`
154 tags_pks = [tag.pk for tag in tags]
156 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
157 if tag_pk in tags_pks:
159 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
160 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
161 related_tags = [tag for tag in related_tags if tag not in tags]
162 for tag in related_tags:
163 tag.count = related_counts[tag.pk]
165 categories = split_tags(related_tags)
169 only_author = len(tags) == 1 and tags[0].category == 'author'
170 objects = models.Book.objects.none()
173 objects = MultiQuerySet(Picture.tagged.with_all(tags), objects)
175 return render_to_response('catalogue/tagged_object_list.html',
177 'object_list': objects,
178 'categories': categories,
179 'only_shelf': only_shelf,
180 'only_author': only_author,
181 'only_my_shelf': only_my_shelf,
182 'formats_form': forms.DownloadFormatsForm(),
185 context_instance=RequestContext(request))
188 def book_fragments(request, slug, theme_slug):
189 book = get_object_or_404(models.Book, slug=slug)
191 book_tag = book.book_tag()
192 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
193 fragments = models.Fragment.tagged.with_all([book_tag, theme])
195 return render_to_response('catalogue/book_fragments.html', locals(),
196 context_instance=RequestContext(request))
199 def book_detail(request, slug):
201 book = models.Book.objects.get(slug=slug)
202 except models.Book.DoesNotExist:
203 return pdcounter_views.book_stub_detail(request, kwargs['slug'])
205 book_tag = book.book_tag()
206 tags = list(book.tags.filter(~Q(category='set')))
207 categories = split_tags(tags)
208 book_children = book.children.all().order_by('parent_number', 'sort_key')
213 parents.append(_book.parent)
215 parents = reversed(parents)
217 theme_counter = book.theme_counter
218 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
219 for tag in book_themes:
220 tag.count = theme_counter[tag.pk]
222 extra_info = book.get_extra_info_value()
223 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
225 custom_pdf_form = forms.CustomPDFForm()
226 return render_to_response('catalogue/book_detail.html', locals(),
227 context_instance=RequestContext(request))
230 def player(request, slug):
231 book = get_object_or_404(models.Book, slug=slug)
232 if not book.has_media('mp3'):
236 for m in book.media.filter(type='ogg').order_by():
237 ogg_files[m.name] = m
242 for mp3 in book.media.filter(type='mp3'):
243 # ogg files are always from the same project
244 meta = mp3.get_extra_info_value()
245 project = meta.get('project')
248 project = u'CzytamySłuchając'
250 projects.add((project, meta.get('funded_by', '')))
254 ogg = ogg_files.get(mp3.name)
259 audiobooks.append(media)
262 projects = sorted(projects)
264 return render_to_response('catalogue/player.html', locals(),
265 context_instance=RequestContext(request))
268 def book_text(request, slug):
269 book = get_object_or_404(models.Book, slug=slug)
271 if not book.has_html_file():
274 for fragment in book.fragments.all():
275 for theme in fragment.tags.filter(category='theme'):
276 book_themes.setdefault(theme, []).append(fragment)
278 book_themes = book_themes.items()
279 book_themes.sort(key=lambda s: s[0].sort_key)
280 return render_to_response('catalogue/book_text.html', locals(),
281 context_instance=RequestContext(request))
288 def _no_diacritics_regexp(query):
289 """ returns a regexp for searching for a query without diacritics
291 should be locale-aware """
293 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źżŹŻ',
294 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
298 return u"(%s)" % '|'.join(names[l])
299 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
301 def unicode_re_escape(query):
302 """ Unicode-friendly version of re.escape """
303 return re.sub('(?u)(\W)', r'\\\1', query)
305 def _word_starts_with(name, prefix):
306 """returns a Q object getting models having `name` contain a word
307 starting with `prefix`
309 We define word characters as alphanumeric and underscore, like in JS.
311 Works for MySQL, PostgreSQL, Oracle.
312 For SQLite, _sqlite* version is substituted for this.
316 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
317 # can't use [[:<:]] (word start),
318 # but we want both `xy` and `(xy` to catch `(xyz)`
319 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
324 def _word_starts_with_regexp(prefix):
325 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
326 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
329 def _sqlite_word_starts_with(name, prefix):
330 """ version of _word_starts_with for SQLite
332 SQLite in Django uses Python re module
335 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
339 if hasattr(settings, 'DATABASES'):
340 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
341 _word_starts_with = _sqlite_word_starts_with
342 elif settings.DATABASE_ENGINE == 'sqlite3':
343 _word_starts_with = _sqlite_word_starts_with
347 def __init__(self, name, view):
350 self.lower = name.lower()
351 self.category = 'application'
353 return reverse(*self._view)
356 App(u'Leśmianator', (u'lesmianator', )),
360 def _tags_starting_with(prefix, user=None):
361 prefix = prefix.lower()
363 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
364 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
366 books = models.Book.objects.filter(_word_starts_with('title', prefix))
367 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
368 if user and user.is_authenticated():
369 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
371 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
373 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
374 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
377 def _get_result_link(match, tag_list):
378 if isinstance(match, models.Tag):
379 return reverse('catalogue.views.tagged_object_list',
380 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
382 elif isinstance(match, App):
385 return match.get_absolute_url()
388 def _get_result_type(match):
389 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
392 type = match.category
396 def books_starting_with(prefix):
397 prefix = prefix.lower()
398 return models.Book.objects.filter(_word_starts_with('title', prefix))
401 def find_best_matches(query, user=None):
402 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
405 - zero elements when nothing is found,
406 - one element when a best result is found,
407 - more then one element on multiple exact matches
409 Raises a ValueError on too short a query.
412 query = query.lower()
414 raise ValueError("query must have at least two characters")
416 result = tuple(_tags_starting_with(query, user))
417 # remove pdcounter stuff
418 book_titles = set(match.pretty_title().lower() for match in result
419 if isinstance(match, models.Book))
420 authors = set(match.name.lower() for match in result
421 if isinstance(match, models.Tag) and match.category=='author')
422 result = tuple(res for res in result if not (
423 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
424 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
427 exact_matches = tuple(res for res in result if res.name.lower() == query)
431 return tuple(result)[:1]
435 tags = request.GET.get('tags', '')
436 prefix = request.GET.get('q', '')
439 tag_list = models.Tag.get_tag_list(tags)
444 result = find_best_matches(prefix, request.user)
446 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
447 context_instance=RequestContext(request))
450 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
451 elif len(result) > 1:
452 return render_to_response('catalogue/search_multiple_hits.html',
453 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
454 context_instance=RequestContext(request))
456 form = PublishingSuggestForm(initial={"books": prefix + ", "})
457 return render_to_response('catalogue/search_no_hits.html',
458 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
459 context_instance=RequestContext(request))
462 def tags_starting_with(request):
463 prefix = request.GET.get('q', '')
464 # Prefix must have at least 2 characters
466 return HttpResponse('')
469 for tag in _tags_starting_with(prefix, request.user):
470 if not tag.name in tags_list:
471 result += "\n" + tag.name
472 tags_list.append(tag.name)
473 return HttpResponse(result)
475 def json_tags_starting_with(request, callback=None):
477 prefix = request.GET.get('q', '')
478 callback = request.GET.get('callback', '')
479 # Prefix must have at least 2 characters
481 return HttpResponse('')
483 for tag in _tags_starting_with(prefix, request.user):
484 if not tag.name in tags_list:
485 tags_list.append(tag.name)
486 if request.GET.get('mozhint', ''):
487 result = [prefix, tags_list]
489 result = {"matches": tags_list}
490 return JSONResponse(result, callback)
492 # ====================
493 # = Shelf management =
494 # ====================
497 def user_shelves(request):
498 shelves = models.Tag.objects.filter(category='set', user=request.user)
499 new_set_form = forms.NewSetForm()
500 return render_to_response('catalogue/user_shelves.html', locals(),
501 context_instance=RequestContext(request))
504 def book_sets(request, slug):
505 if not request.user.is_authenticated():
506 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
508 book = get_object_or_404(models.Book, slug=slug)
510 user_sets = models.Tag.objects.filter(category='set', user=request.user)
511 book_sets = book.tags.filter(category='set', user=request.user)
513 if request.method == 'POST':
514 form = forms.ObjectSetsForm(book, request.user, request.POST)
516 old_shelves = list(book.tags.filter(category='set'))
517 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
519 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
522 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
525 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
526 if request.is_ajax():
527 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
529 return HttpResponseRedirect('/')
531 form = forms.ObjectSetsForm(book, request.user)
532 new_set_form = forms.NewSetForm()
534 return render_to_response('catalogue/book_sets.html', locals(),
535 context_instance=RequestContext(request))
541 def remove_from_shelf(request, shelf, slug):
542 book = get_object_or_404(models.Book, slug=slug)
544 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
546 if shelf in book.tags:
547 models.Tag.objects.remove_tag(book, shelf)
550 return HttpResponse(_('Book was successfully removed from the shelf'))
552 return HttpResponse(_('This book is not on the shelf'))
555 def collect_books(books):
557 Returns all real books in collection.
561 if len(book.children.all()) == 0:
564 result += collect_books(book.children.all())
569 def download_shelf(request, slug):
571 Create a ZIP archive on disk and transmit it in chunks of 8KB,
572 without loading the whole file into memory. A similar approach can
573 be used for large dynamic PDF files.
575 from slughifi import slughifi
579 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
582 form = forms.DownloadFormatsForm(request.GET)
584 formats = form.cleaned_data['formats']
585 if len(formats) == 0:
586 formats = models.Book.ebook_formats
588 # Create a ZIP archive
589 temp = tempfile.TemporaryFile()
590 archive = zipfile.ZipFile(temp, 'w')
592 for book in collect_books(models.Book.tagged.with_all(shelf)):
593 for ebook_format in models.Book.ebook_formats:
594 if ebook_format in formats and book.has_media(ebook_format):
595 filename = book.get_media(ebook_format).path
596 archive.write(filename, str('%s.%s' % (book.slug, ebook_format)))
599 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
600 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
601 response['Content-Length'] = temp.tell()
604 response.write(temp.read())
609 def shelf_book_formats(request, shelf):
611 Returns a list of formats of books in shelf.
613 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
616 for ebook_format in models.Book.ebook_formats:
617 formats[ebook_format] = False
619 for book in collect_books(models.Book.tagged.with_all(shelf)):
620 for ebook_format in models.Book.ebook_formats:
621 if book.has_media(ebook_format):
622 formats[ebook_format] = True
624 return HttpResponse(LazyEncoder().encode(formats))
630 def new_set(request):
631 new_set_form = forms.NewSetForm(request.POST)
632 if new_set_form.is_valid():
633 new_set = new_set_form.save(request.user)
635 if request.is_ajax():
636 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
638 return HttpResponseRedirect('/')
640 return HttpResponseRedirect('/')
646 def delete_shelf(request, slug):
647 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
650 if request.is_ajax():
651 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
653 return HttpResponseRedirect('/')
661 def import_book(request):
662 """docstring for import_book"""
663 book_import_form = forms.BookImportForm(request.POST, request.FILES)
664 if book_import_form.is_valid():
666 book_import_form.save()
671 info = sys.exc_info()
672 exception = pprint.pformat(info[1])
673 tb = '\n'.join(traceback.format_tb(info[2]))
674 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
675 return HttpResponse(_("Book imported successfully"))
677 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
682 def book_info(request, id, lang='pl'):
683 book = get_object_or_404(models.Book, id=id)
684 # set language by hand
685 translation.activate(lang)
686 return render_to_response('catalogue/book_info.html', locals(),
687 context_instance=RequestContext(request))
690 def tag_info(request, id):
691 tag = get_object_or_404(models.Tag, id=id)
692 return HttpResponse(tag.description)
695 def download_zip(request, format, slug=None):
697 if format in models.Book.ebook_formats:
698 url = models.Book.zip_format(format)
699 elif format in ('mp3', 'ogg') and slug is not None:
700 book = get_object_or_404(models.Book, slug=slug)
701 url = book.zip_audiobooks(format)
703 raise Http404('No format specified for zip package')
704 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
707 def download_custom_pdf(request, slug):
708 book = get_object_or_404(models.Book, slug=slug)
710 if request.method == 'GET':
711 form = forms.CustomPDFForm(request.GET)
713 cust = form.customizations
714 pdf_file = models.get_customized_pdf_path(book, cust)
716 if not path.exists(pdf_file):
717 result = async_build_pdf.delay(book.id, cust, pdf_file)
719 return AttachmentHttpResponse(file_name=("%s.pdf" % book.slug), file_path=pdf_file, mimetype="application/pdf")
721 raise Http404(_('Incorrect customization options for PDF'))
723 raise Http404(_('Bad method'))