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
32 from pdcounter import models as pdcounter_models
33 from pdcounter import views as pdcounter_views
34 from suggest.forms import PublishingSuggestForm
37 staff_required = user_passes_test(lambda user: user.is_staff)
40 class LazyEncoder(simplejson.JSONEncoder):
41 def default(self, obj):
42 if isinstance(obj, Promise):
43 return force_unicode(obj)
46 # shortcut for JSON reponses
47 class JSONResponse(HttpResponse):
48 def __init__(self, data={}, callback=None, **kwargs):
50 kwargs.pop('mimetype', None)
51 data = simplejson.dumps(data)
53 data = callback + "(" + data + ");"
54 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
57 def main_page(request):
58 if request.user.is_authenticated():
59 shelves = models.Tag.objects.filter(category='set', user=request.user)
60 new_set_form = forms.NewSetForm()
62 tags = models.Tag.objects.exclude(category__in=('set', 'book'))
64 tag.count = tag.get_count()
65 categories = split_tags(tags)
66 fragment_tags = categories.get('theme', [])
68 form = forms.SearchForm()
69 return render_to_response('catalogue/main_page.html', locals(),
70 context_instance=RequestContext(request))
73 def book_list(request, filter=None, template_name='catalogue/book_list.html',
75 """ generates a listing of all books, optionally filtered with a test function """
77 form = forms.SearchForm()
79 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
80 books_nav = SortedDict()
81 for tag in books_by_author:
82 if books_by_author[tag]:
83 books_nav.setdefault(tag.sort_key[0], []).append(tag)
85 return render_to_response(template_name, locals(),
86 context_instance=RequestContext(request))
89 def audiobook_list(request):
90 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
91 template_name='catalogue/audiobook_list.html')
94 def daisy_list(request):
95 return book_list(request, Q(media__type='daisy'),
96 template_name='catalogue/daisy_list.html')
99 def collection(request, slug):
100 coll = get_object_or_404(models.Collection, slug=slug)
101 slugs = coll.book_slugs.split()
103 slugs = [slug.rstrip('/').rsplit('/', 1)[-1] if '/' in slug else slug
105 return book_list(request, Q(slug__in=slugs),
106 template_name='catalogue/collection.html',
107 context={'collection': coll})
110 def differentiate_tags(request, tags, ambiguous_slugs):
111 beginning = '/'.join(tag.url_chunk for tag in tags)
112 unparsed = '/'.join(ambiguous_slugs[1:])
114 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
116 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
119 return render_to_response('catalogue/differentiate_tags.html',
120 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
121 context_instance=RequestContext(request))
124 def tagged_object_list(request, tags=''):
126 tags = models.Tag.get_tag_list(tags)
127 except models.Tag.DoesNotExist:
128 chunks = tags.split('/')
129 if len(chunks) == 2 and chunks[0] == 'autor':
130 return pdcounter_views.author_detail(request, chunks[1])
133 except models.Tag.MultipleObjectsReturned, e:
134 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
135 except models.Tag.UrlDeprecationWarning, e:
136 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
139 if len(tags) > settings.MAX_TAG_LIST:
141 except AttributeError:
144 if len([tag for tag in tags if tag.category == 'book']):
147 theme_is_set = [tag for tag in tags if tag.category == 'theme']
148 shelf_is_set = [tag for tag in tags if tag.category == 'set']
149 only_shelf = shelf_is_set and len(tags) == 1
150 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
152 objects = only_author = None
156 shelf_tags = [tag for tag in tags if tag.category == 'set']
157 fragment_tags = [tag for tag in tags if tag.category != 'set']
158 fragments = models.Fragment.tagged.with_all(fragment_tags)
161 books = models.Book.tagged.with_all(shelf_tags).order_by()
162 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
163 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
165 # newtagging goes crazy if we just try:
166 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
167 # extra={'where': ["catalogue_tag.category != 'book'"]})
168 fragment_keys = [fragment.pk for fragment in fragments]
170 related_tags = models.Fragment.tags.usage(counts=True,
171 filters={'pk__in': fragment_keys},
172 extra={'where': ["catalogue_tag.category != 'book'"]})
173 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
174 categories = split_tags(related_tags)
179 objects = models.Book.tagged.with_all(tags)
181 objects = models.Book.tagged_top_level(tags)
183 # get related tags from `tag_counter` and `theme_counter`
185 tags_pks = [tag.pk for tag in tags]
187 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
188 if tag_pk in tags_pks:
190 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
191 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
192 related_tags = [tag for tag in related_tags if tag not in tags]
193 for tag in related_tags:
194 tag.count = related_counts[tag.pk]
196 categories = split_tags(related_tags)
200 only_author = len(tags) == 1 and tags[0].category == 'author'
201 objects = models.Book.objects.none()
206 template_name='catalogue/tagged_object_list.html',
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(),
218 def book_fragments(request, book_slug, theme_slug):
219 book = get_object_or_404(models.Book, slug=book_slug)
220 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
221 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
222 fragments = models.Fragment.tagged.with_all([book_tag, theme])
224 form = forms.SearchForm()
225 return render_to_response('catalogue/book_fragments.html', locals(),
226 context_instance=RequestContext(request))
229 def book_detail(request, slug):
231 book = models.Book.objects.get(slug=slug)
232 except models.Book.DoesNotExist:
233 return pdcounter_views.book_stub_detail(request, slug)
235 book_tag = book.book_tag()
236 tags = list(book.tags.filter(~Q(category='set')))
237 categories = split_tags(tags)
238 book_children = book.children.all().order_by('parent_number', 'sort_key')
243 parents.append(_book.parent)
245 parents = reversed(parents)
247 theme_counter = book.theme_counter
248 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
249 for tag in book_themes:
250 tag.count = theme_counter[tag.pk]
252 extra_info = book.get_extra_info_value()
253 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
256 for m in book.media.filter(type='mp3'):
257 # ogg files are always from the same project
258 meta = m.get_extra_info_value()
259 project = meta.get('project')
262 project = u'CzytamySłuchając'
264 projects.add((project, meta.get('funded_by', '')))
265 projects = sorted(projects)
267 form = forms.SearchForm()
268 return render_to_response('catalogue/book_detail.html', locals(),
269 context_instance=RequestContext(request))
272 def book_text(request, slug):
273 book = get_object_or_404(models.Book, slug=slug)
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 Book, Tag, 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, slug):
508 if not request.user.is_authenticated():
509 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
511 book = get_object_or_404(models.Book, slug=slug)
512 user_sets = models.Tag.objects.filter(category='set', user=request.user)
513 book_sets = book.tags.filter(category='set', user=request.user)
515 if request.method == 'POST':
516 form = forms.ObjectSetsForm(book, request.user, request.POST)
518 old_shelves = list(book.tags.filter(category='set'))
519 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
521 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
522 shelf.book_count = None
525 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
526 shelf.book_count = None
529 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
530 if request.is_ajax():
531 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
533 return HttpResponseRedirect('/')
535 form = forms.ObjectSetsForm(book, request.user)
536 new_set_form = forms.NewSetForm()
538 return render_to_response('catalogue/book_sets.html', locals(),
539 context_instance=RequestContext(request))
545 def remove_from_shelf(request, shelf, book):
546 book = get_object_or_404(models.Book, slug=book)
547 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
549 if shelf in book.tags:
550 models.Tag.objects.remove_tag(book, shelf)
552 shelf.book_count = None
555 return HttpResponse(_('Book was successfully removed from the shelf'))
557 return HttpResponse(_('This book is not on the shelf'))
560 def collect_books(books):
562 Returns all real books in collection.
566 if len(book.children.all()) == 0:
569 result += collect_books(book.children.all())
574 def download_shelf(request, slug):
576 Create a ZIP archive on disk and transmit it in chunks of 8KB,
577 without loading the whole file into memory. A similar approach can
578 be used for large dynamic PDF files.
580 from slughifi import slughifi
584 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
587 form = forms.DownloadFormatsForm(request.GET)
589 formats = form.cleaned_data['formats']
590 if len(formats) == 0:
591 formats = ['pdf', 'epub', 'mobi', 'odt', 'txt']
593 # Create a ZIP archive
594 temp = tempfile.TemporaryFile()
595 archive = zipfile.ZipFile(temp, 'w')
598 for book in collect_books(models.Book.tagged.with_all(shelf)):
599 if 'pdf' in formats and book.pdf_file:
600 filename = book.pdf_file.path
601 archive.write(filename, str('%s.pdf' % book.slug))
602 if 'mobi' in formats and book.mobi_file:
603 filename = book.mobi_file.path
604 archive.write(filename, str('%s.mobi' % book.slug))
605 if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
606 filename = book.root_ancestor.epub_file.path
607 archive.write(filename, str('%s.epub' % book.root_ancestor.slug))
608 already.add(book.root_ancestor)
609 if 'odt' in formats and book.has_media("odt"):
610 for file in book.get_media("odt"):
611 filename = file.file.path
612 archive.write(filename, str('%s.odt' % slughifi(file.name)))
613 if 'txt' in formats and book.txt_file:
614 filename = book.txt_file.path
615 archive.write(filename, str('%s.txt' % book.slug))
618 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
619 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
620 response['Content-Length'] = temp.tell()
623 response.write(temp.read())
628 def shelf_book_formats(request, shelf):
630 Returns a list of formats of books in shelf.
632 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
634 formats = {'pdf': False, 'epub': False, 'mobi': False, 'odt': False, 'txt': False}
636 for book in collect_books(models.Book.tagged.with_all(shelf)):
638 formats['pdf'] = True
639 if book.root_ancestor.epub_file:
640 formats['epub'] = True
642 formats['mobi'] = True
644 formats['txt'] = True
645 for format in ('odt',):
646 if book.has_media(format):
647 formats[format] = True
649 return HttpResponse(LazyEncoder().encode(formats))
655 def new_set(request):
656 new_set_form = forms.NewSetForm(request.POST)
657 if new_set_form.is_valid():
658 new_set = new_set_form.save(request.user)
660 if request.is_ajax():
661 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
663 return HttpResponseRedirect('/')
665 return HttpResponseRedirect('/')
671 def delete_shelf(request, slug):
672 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
675 if request.is_ajax():
676 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
678 return HttpResponseRedirect('/')
687 form = AuthenticationForm(data=request.POST, prefix='login')
689 auth.login(request, form.get_user())
690 response_data = {'success': True, 'errors': {}}
692 response_data = {'success': False, 'errors': form.errors}
693 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
698 def register(request):
699 registration_form = UserCreationForm(request.POST, prefix='registration')
700 if registration_form.is_valid():
701 user = registration_form.save()
702 user = auth.authenticate(
703 username=registration_form.cleaned_data['username'],
704 password=registration_form.cleaned_data['password1']
706 auth.login(request, user)
707 response_data = {'success': True, 'errors': {}}
709 response_data = {'success': False, 'errors': registration_form.errors}
710 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
714 def logout_then_redirect(request):
716 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
725 def import_book(request):
726 """docstring for import_book"""
727 book_import_form = forms.BookImportForm(request.POST, request.FILES)
728 if book_import_form.is_valid():
730 book_import_form.save()
735 info = sys.exc_info()
736 exception = pprint.pformat(info[1])
737 tb = '\n'.join(traceback.format_tb(info[2]))
738 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
739 return HttpResponse(_("Book imported successfully"))
741 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
746 """ Provides server time for jquery.countdown,
747 in a format suitable for Date.parse()
749 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
754 def book_info(request, id, lang='pl'):
755 book = get_object_or_404(models.Book, id=id)
756 # set language by hand
757 translation.activate(lang)
758 return render_to_response('catalogue/book_info.html', locals(),
759 context_instance=RequestContext(request))
762 def tag_info(request, id):
763 tag = get_object_or_404(models.Tag, id=id)
764 return HttpResponse(tag.description)
767 def download_zip(request, format, slug):
769 if format in ('pdf', 'epub', 'mobi'):
770 url = models.Book.zip_format(format)
771 elif format == 'audiobook' and slug is not None:
772 book = models.Book.objects.get(slug=slug)
773 url = book.zip_audiobooks()
775 raise Http404('No format specified for zip package')
776 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))