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 import simplejson
21 from django.utils.functional import Promise
22 from django.utils.encoding import force_unicode
23 from django.utils.http import urlquote_plus
24 from django.views.decorators import cache
25 from django.utils import translation
26 from django.utils.translation import ugettext as _
27 from django.views.generic.list_detail import object_list
29 from catalogue import models
30 from catalogue import forms
31 from catalogue.utils import split_tags, AttachmentHttpResponse, async_build_pdf
32 from catalogue.tasks import touch_tag
33 from pdcounter import models as pdcounter_models
34 from pdcounter import views as pdcounter_views
35 from suggest.forms import PublishingSuggestForm
39 staff_required = user_passes_test(lambda user: user.is_staff)
42 class LazyEncoder(simplejson.JSONEncoder):
43 def default(self, obj):
44 if isinstance(obj, Promise):
45 return force_unicode(obj)
48 # shortcut for JSON reponses
49 class JSONResponse(HttpResponse):
50 def __init__(self, data={}, callback=None, **kwargs):
52 kwargs.pop('mimetype', None)
53 data = simplejson.dumps(data)
55 data = callback + "(" + data + ");"
56 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
59 def catalogue(request):
60 tags = models.Tag.objects.exclude(
61 category__in=('set', 'book')).exclude(book_count=0)
64 tag.count = tag.book_count
65 categories = split_tags(tags)
66 fragment_tags = categories.get('theme', [])
68 form = forms.SearchForm()
69 return render_to_response('catalogue/catalogue.html', locals(),
70 context_instance=RequestContext(request))
73 def book_list(request, filter=None, template_name='catalogue/book_list.html'):
74 """ generates a listing of all books, optionally filtered with a test function """
76 form = forms.SearchForm()
78 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
79 books_nav = SortedDict()
80 for tag in books_by_author:
81 if books_by_author[tag]:
82 books_nav.setdefault(tag.sort_key[0], []).append(tag)
84 return render_to_response(template_name, locals(),
85 context_instance=RequestContext(request))
88 def audiobook_list(request):
89 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
90 template_name='catalogue/audiobook_list.html')
93 def daisy_list(request):
94 return book_list(request, Q(media__type='daisy'),
95 template_name='catalogue/daisy_list.html')
98 def differentiate_tags(request, tags, ambiguous_slugs):
99 beginning = '/'.join(tag.url_chunk for tag in tags)
100 unparsed = '/'.join(ambiguous_slugs[1:])
102 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
104 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
107 return render_to_response('catalogue/differentiate_tags.html',
108 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
109 context_instance=RequestContext(request))
112 def tagged_object_list(request, tags=''):
114 tags = models.Tag.get_tag_list(tags)
115 except models.Tag.DoesNotExist:
116 chunks = tags.split('/')
117 if len(chunks) == 2 and chunks[0] == 'autor':
118 return pdcounter_views.author_detail(request, chunks[1])
121 except models.Tag.MultipleObjectsReturned, e:
122 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
123 except models.Tag.UrlDeprecationWarning, e:
124 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
127 if len(tags) > settings.MAX_TAG_LIST:
129 except AttributeError:
132 if len([tag for tag in tags if tag.category == 'book']):
135 theme_is_set = [tag for tag in tags if tag.category == 'theme']
136 shelf_is_set = [tag for tag in tags if tag.category == 'set']
137 only_shelf = shelf_is_set and len(tags) == 1
138 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
140 objects = only_author = None
144 shelf_tags = [tag for tag in tags if tag.category == 'set']
145 fragment_tags = [tag for tag in tags if tag.category != 'set']
146 fragments = models.Fragment.tagged.with_all(fragment_tags)
149 books = models.Book.tagged.with_all(shelf_tags).order_by()
150 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
151 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
153 # newtagging goes crazy if we just try:
154 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
155 # extra={'where': ["catalogue_tag.category != 'book'"]})
156 fragment_keys = [fragment.pk for fragment in fragments]
158 related_tags = models.Fragment.tags.usage(counts=True,
159 filters={'pk__in': fragment_keys},
160 extra={'where': ["catalogue_tag.category != 'book'"]})
161 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
162 categories = split_tags(related_tags)
167 objects = models.Book.tagged.with_all(tags)
169 objects = models.Book.tagged_top_level(tags)
171 # get related tags from `tag_counter` and `theme_counter`
173 tags_pks = [tag.pk for tag in tags]
175 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
176 if tag_pk in tags_pks:
178 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
179 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
180 related_tags = [tag for tag in related_tags if tag not in tags]
181 for tag in related_tags:
182 tag.count = related_counts[tag.pk]
184 categories = split_tags(related_tags)
188 only_author = len(tags) == 1 and tags[0].category == 'author'
189 objects = models.Book.objects.none()
194 template_name='catalogue/tagged_object_list.html',
196 'categories': categories,
197 'only_shelf': only_shelf,
198 'only_author': only_author,
199 'only_my_shelf': only_my_shelf,
200 'formats_form': forms.DownloadFormatsForm(),
206 def book_fragments(request, book, theme_slug):
207 kwargs = models.Book.split_urlid(book)
210 book = get_object_or_404(models.Book, **kwargs)
212 book_tag = book.book_tag()
213 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
214 fragments = models.Fragment.tagged.with_all([book_tag, theme])
216 form = forms.SearchForm()
217 return render_to_response('catalogue/book_fragments.html', locals(),
218 context_instance=RequestContext(request))
221 def book_detail(request, book):
222 kwargs = models.Book.split_urlid(book)
226 book = models.Book.objects.get(**kwargs)
227 except models.Book.DoesNotExist:
228 return pdcounter_views.book_stub_detail(request, kwargs['slug'])
230 book_tag = book.book_tag()
231 tags = list(book.tags.filter(~Q(category='set')))
232 categories = split_tags(tags)
233 book_children = book.children.all().order_by('parent_number', 'sort_key')
238 parents.append(_book.parent)
240 parents = reversed(parents)
242 theme_counter = book.theme_counter
243 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
244 for tag in book_themes:
245 tag.count = theme_counter[tag.pk]
247 extra_info = book.get_extra_info_value()
248 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
251 for m in book.media.filter(type='mp3'):
252 # ogg files are always from the same project
253 meta = m.get_extra_info_value()
254 project = meta.get('project')
257 project = u'CzytamySłuchając'
259 projects.add((project, meta.get('funded_by', '')))
260 projects = sorted(projects)
262 form = forms.SearchForm()
263 custom_pdf_form = forms.CustomPDFForm()
264 return render_to_response('catalogue/book_detail.html', locals(),
265 context_instance=RequestContext(request))
268 def book_text(request, book):
269 kwargs = models.Book.split_fileid(book)
272 book = get_object_or_404(models.Book, **kwargs)
274 if not book.has_html_file():
277 for fragment in book.fragments.all():
278 for theme in fragment.tags.filter(category='theme'):
279 book_themes.setdefault(theme, []).append(fragment)
281 book_themes = book_themes.items()
282 book_themes.sort(key=lambda s: s[0].sort_key)
283 return render_to_response('catalogue/book_text.html', locals(),
284 context_instance=RequestContext(request))
291 def _no_diacritics_regexp(query):
292 """ returns a regexp for searching for a query without diacritics
294 should be locale-aware """
296 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źżŹŻ',
297 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
301 return u"(%s)" % '|'.join(names[l])
302 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
304 def unicode_re_escape(query):
305 """ Unicode-friendly version of re.escape """
306 return re.sub('(?u)(\W)', r'\\\1', query)
308 def _word_starts_with(name, prefix):
309 """returns a Q object getting models having `name` contain a word
310 starting with `prefix`
312 We define word characters as alphanumeric and underscore, like in JS.
314 Works for MySQL, PostgreSQL, Oracle.
315 For SQLite, _sqlite* version is substituted for this.
319 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
320 # can't use [[:<:]] (word start),
321 # but we want both `xy` and `(xy` to catch `(xyz)`
322 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
327 def _word_starts_with_regexp(prefix):
328 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
329 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
332 def _sqlite_word_starts_with(name, prefix):
333 """ version of _word_starts_with for SQLite
335 SQLite in Django uses Python re module
338 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
342 if hasattr(settings, 'DATABASES'):
343 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
344 _word_starts_with = _sqlite_word_starts_with
345 elif settings.DATABASE_ENGINE == 'sqlite3':
346 _word_starts_with = _sqlite_word_starts_with
350 def __init__(self, name, view):
353 self.lower = name.lower()
354 self.category = 'application'
356 return reverse(*self._view)
359 App(u'Leśmianator', (u'lesmianator', )),
363 def _tags_starting_with(prefix, user=None):
364 prefix = prefix.lower()
366 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
367 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
369 books = models.Book.objects.filter(_word_starts_with('title', prefix))
370 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
371 if user and user.is_authenticated():
372 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
374 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
376 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
377 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
380 def _get_result_link(match, tag_list):
381 if isinstance(match, models.Tag):
382 return reverse('catalogue.views.tagged_object_list',
383 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
385 elif isinstance(match, App):
388 return match.get_absolute_url()
391 def _get_result_type(match):
392 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
395 type = match.category
399 def books_starting_with(prefix):
400 prefix = prefix.lower()
401 return models.Book.objects.filter(_word_starts_with('title', prefix))
404 def find_best_matches(query, user=None):
405 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
408 - zero elements when nothing is found,
409 - one element when a best result is found,
410 - more then one element on multiple exact matches
412 Raises a ValueError on too short a query.
415 query = query.lower()
417 raise ValueError("query must have at least two characters")
419 result = tuple(_tags_starting_with(query, user))
420 # remove pdcounter stuff
421 book_titles = set(match.pretty_title().lower() for match in result
422 if isinstance(match, models.Book))
423 authors = set(match.name.lower() for match in result
424 if isinstance(match, models.Tag) and match.category=='author')
425 result = tuple(res for res in result if not (
426 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
427 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
430 exact_matches = tuple(res for res in result if res.name.lower() == query)
434 return tuple(result)[:1]
438 tags = request.GET.get('tags', '')
439 prefix = request.GET.get('q', '')
442 tag_list = models.Tag.get_tag_list(tags)
447 result = find_best_matches(prefix, request.user)
449 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
450 context_instance=RequestContext(request))
453 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
454 elif len(result) > 1:
455 return render_to_response('catalogue/search_multiple_hits.html',
456 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
457 context_instance=RequestContext(request))
459 form = PublishingSuggestForm(initial={"books": prefix + ", "})
460 return render_to_response('catalogue/search_no_hits.html',
461 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
462 context_instance=RequestContext(request))
465 def tags_starting_with(request):
466 prefix = request.GET.get('q', '')
467 # Prefix must have at least 2 characters
469 return HttpResponse('')
472 for tag in _tags_starting_with(prefix, request.user):
473 if not tag.name in tags_list:
474 result += "\n" + tag.name
475 tags_list.append(tag.name)
476 return HttpResponse(result)
478 def json_tags_starting_with(request, callback=None):
480 prefix = request.GET.get('q', '')
481 callback = request.GET.get('callback', '')
482 # Prefix must have at least 2 characters
484 return HttpResponse('')
486 for tag in _tags_starting_with(prefix, request.user):
487 if not tag.name in tags_list:
488 tags_list.append(tag.name)
489 if request.GET.get('mozhint', ''):
490 result = [prefix, tags_list]
492 result = {"matches": tags_list}
493 return JSONResponse(result, callback)
495 # ====================
496 # = Shelf management =
497 # ====================
500 def user_shelves(request):
501 shelves = models.Tag.objects.filter(category='set', user=request.user)
502 new_set_form = forms.NewSetForm()
503 return render_to_response('catalogue/user_shelves.html', locals(),
504 context_instance=RequestContext(request))
507 def book_sets(request, book):
508 if not request.user.is_authenticated():
509 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
511 kwargs = models.Book.split_urlid(book)
514 book = get_object_or_404(models.Book, **kwargs)
516 user_sets = models.Tag.objects.filter(category='set', user=request.user)
517 book_sets = book.tags.filter(category='set', user=request.user)
519 if request.method == 'POST':
520 form = forms.ObjectSetsForm(book, request.user, request.POST)
522 old_shelves = list(book.tags.filter(category='set'))
523 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
525 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
528 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
531 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
532 if request.is_ajax():
533 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
535 return HttpResponseRedirect('/')
537 form = forms.ObjectSetsForm(book, request.user)
538 new_set_form = forms.NewSetForm()
540 return render_to_response('catalogue/book_sets.html', locals(),
541 context_instance=RequestContext(request))
547 def remove_from_shelf(request, shelf, book):
548 kwargs = models.Book.split_urlid(book)
551 book = get_object_or_404(models.Book, **kwargs)
553 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
555 if shelf in book.tags:
556 models.Tag.objects.remove_tag(book, shelf)
559 return HttpResponse(_('Book was successfully removed from the shelf'))
561 return HttpResponse(_('This book is not on the shelf'))
564 def collect_books(books):
566 Returns all real books in collection.
570 if len(book.children.all()) == 0:
573 result += collect_books(book.children.all())
578 def download_shelf(request, slug):
580 Create a ZIP archive on disk and transmit it in chunks of 8KB,
581 without loading the whole file into memory. A similar approach can
582 be used for large dynamic PDF files.
584 from slughifi import slughifi
588 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
591 form = forms.DownloadFormatsForm(request.GET)
593 formats = form.cleaned_data['formats']
594 if len(formats) == 0:
595 formats = models.Book.ebook_formats
597 # Create a ZIP archive
598 temp = tempfile.TemporaryFile()
599 archive = zipfile.ZipFile(temp, 'w')
601 for book in collect_books(models.Book.tagged.with_all(shelf)):
602 fileid = book.fileid()
603 for ebook_format in models.Book.ebook_formats:
604 if ebook_format in formats and book.has_media(ebook_format):
605 filename = book.get_media(ebook_format).path
606 archive.write(filename, str('%s.%s' % (fileid, ebook_format)))
609 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
610 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
611 response['Content-Length'] = temp.tell()
614 response.write(temp.read())
619 def shelf_book_formats(request, shelf):
621 Returns a list of formats of books in shelf.
623 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
626 for ebook_format in models.Book.ebook_formats:
627 formats[ebook_format] = False
629 for book in collect_books(models.Book.tagged.with_all(shelf)):
630 for ebook_format in models.Book.ebook_formats:
631 if book.has_media(ebook_format):
632 formats[ebook_format] = True
634 return HttpResponse(LazyEncoder().encode(formats))
640 def new_set(request):
641 new_set_form = forms.NewSetForm(request.POST)
642 if new_set_form.is_valid():
643 new_set = new_set_form.save(request.user)
645 if request.is_ajax():
646 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
648 return HttpResponseRedirect('/')
650 return HttpResponseRedirect('/')
656 def delete_shelf(request, slug):
657 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
660 if request.is_ajax():
661 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
663 return HttpResponseRedirect('/')
672 form = AuthenticationForm(data=request.POST, prefix='login')
674 auth.login(request, form.get_user())
675 response_data = {'success': True, 'errors': {}}
677 response_data = {'success': False, 'errors': form.errors}
678 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
683 def register(request):
684 registration_form = UserCreationForm(request.POST, prefix='registration')
685 if registration_form.is_valid():
686 user = registration_form.save()
687 user = auth.authenticate(
688 username=registration_form.cleaned_data['username'],
689 password=registration_form.cleaned_data['password1']
691 auth.login(request, user)
692 response_data = {'success': True, 'errors': {}}
694 response_data = {'success': False, 'errors': registration_form.errors}
695 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
699 def logout_then_redirect(request):
701 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
710 def import_book(request):
711 """docstring for import_book"""
712 book_import_form = forms.BookImportForm(request.POST, request.FILES)
713 if book_import_form.is_valid():
715 book_import_form.save()
720 info = sys.exc_info()
721 exception = pprint.pformat(info[1])
722 tb = '\n'.join(traceback.format_tb(info[2]))
723 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
724 return HttpResponse(_("Book imported successfully"))
726 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
731 """ Provides server time for jquery.countdown,
732 in a format suitable for Date.parse()
734 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
739 def book_info(request, id, lang='pl'):
740 book = get_object_or_404(models.Book, id=id)
741 # set language by hand
742 translation.activate(lang)
743 return render_to_response('catalogue/book_info.html', locals(),
744 context_instance=RequestContext(request))
747 def tag_info(request, id):
748 tag = get_object_or_404(models.Tag, id=id)
749 return HttpResponse(tag.description)
752 def download_zip(request, format, book=None):
753 kwargs = models.Book.split_fileid(book)
756 if format in models.Book.ebook_formats:
757 url = models.Book.zip_format(format)
758 elif format == 'audiobook' and kwargs is not None:
759 book = get_object_or_404(models.Book, **kwargs)
760 url = book.zip_audiobooks()
762 raise Http404('No format specified for zip package')
763 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
766 def download_custom_pdf(request, book_fileid):
767 kwargs = models.Book.split_fileid(book_fileid)
770 book = get_object_or_404(models.Book, **kwargs)
772 if request.method == 'GET':
773 form = forms.CustomPDFForm(request.GET)
775 cust = form.customizations
776 pdf_file = models.get_customized_pdf_path(book, cust)
778 if not path.exists(pdf_file):
779 result = async_build_pdf.delay(book.id, cust, pdf_file)
781 return AttachmentHttpResponse(file_name=("%s.pdf" % book_fileid), file_path=pdf_file, mimetype="application/pdf")
783 raise Http404(_('Incorrect customization options for PDF'))
785 raise Http404(_('Bad method'))