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'):
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_slug, theme_slug):
207 book = get_object_or_404(models.Book, slug=book_slug)
208 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
209 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
210 fragments = models.Fragment.tagged.with_all([book_tag, theme])
212 form = forms.SearchForm()
213 return render_to_response('catalogue/book_fragments.html', locals(),
214 context_instance=RequestContext(request))
217 def book_detail(request, slug):
219 book = models.Book.objects.get(slug=slug)
220 except models.Book.DoesNotExist:
221 return pdcounter_views.book_stub_detail(request, slug)
223 book_tag = book.book_tag()
224 tags = list(book.tags.filter(~Q(category='set')))
225 categories = split_tags(tags)
226 book_children = book.children.all().order_by('parent_number', 'sort_key')
231 parents.append(_book.parent)
233 parents = reversed(parents)
235 theme_counter = book.theme_counter
236 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
237 for tag in book_themes:
238 tag.count = theme_counter[tag.pk]
240 extra_info = book.get_extra_info_value()
241 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
244 for m in book.media.filter(type='mp3'):
245 # ogg files are always from the same project
246 meta = m.get_extra_info_value()
247 project = meta.get('project')
250 project = u'CzytamySłuchając'
252 projects.add((project, meta.get('funded_by', '')))
253 projects = sorted(projects)
255 form = forms.SearchForm()
256 return render_to_response('catalogue/book_detail.html', locals(),
257 context_instance=RequestContext(request))
260 def book_text(request, slug):
261 book = get_object_or_404(models.Book, slug=slug)
262 if not book.has_html_file():
265 for fragment in book.fragments.all():
266 for theme in fragment.tags.filter(category='theme'):
267 book_themes.setdefault(theme, []).append(fragment)
269 book_themes = book_themes.items()
270 book_themes.sort(key=lambda s: s[0].sort_key)
271 return render_to_response('catalogue/book_text.html', locals(),
272 context_instance=RequestContext(request))
279 def _no_diacritics_regexp(query):
280 """ returns a regexp for searching for a query without diacritics
282 should be locale-aware """
284 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źżŹŻ',
285 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
289 return u"(%s)" % '|'.join(names[l])
290 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
292 def unicode_re_escape(query):
293 """ Unicode-friendly version of re.escape """
294 return re.sub('(?u)(\W)', r'\\\1', query)
296 def _word_starts_with(name, prefix):
297 """returns a Q object getting models having `name` contain a word
298 starting with `prefix`
300 We define word characters as alphanumeric and underscore, like in JS.
302 Works for MySQL, PostgreSQL, Oracle.
303 For SQLite, _sqlite* version is substituted for this.
307 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
308 # can't use [[:<:]] (word start),
309 # but we want both `xy` and `(xy` to catch `(xyz)`
310 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
315 def _word_starts_with_regexp(prefix):
316 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
317 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
320 def _sqlite_word_starts_with(name, prefix):
321 """ version of _word_starts_with for SQLite
323 SQLite in Django uses Python re module
326 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
330 if hasattr(settings, 'DATABASES'):
331 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
332 _word_starts_with = _sqlite_word_starts_with
333 elif settings.DATABASE_ENGINE == 'sqlite3':
334 _word_starts_with = _sqlite_word_starts_with
338 def __init__(self, name, view):
341 self.lower = name.lower()
342 self.category = 'application'
344 return reverse(*self._view)
347 App(u'Leśmianator', (u'lesmianator', )),
351 def _tags_starting_with(prefix, user=None):
352 prefix = prefix.lower()
354 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
355 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
357 books = models.Book.objects.filter(_word_starts_with('title', prefix))
358 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
359 if user and user.is_authenticated():
360 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
362 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
364 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
365 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
368 def _get_result_link(match, tag_list):
369 if isinstance(match, models.Tag):
370 return reverse('catalogue.views.tagged_object_list',
371 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
373 elif isinstance(match, App):
376 return match.get_absolute_url()
379 def _get_result_type(match):
380 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
383 type = match.category
387 def books_starting_with(prefix):
388 prefix = prefix.lower()
389 return models.Book.objects.filter(_word_starts_with('title', prefix))
392 def find_best_matches(query, user=None):
393 """ Finds a Book, Tag, BookStub or Author best matching a query.
396 - zero elements when nothing is found,
397 - one element when a best result is found,
398 - more then one element on multiple exact matches
400 Raises a ValueError on too short a query.
403 query = query.lower()
405 raise ValueError("query must have at least two characters")
407 result = tuple(_tags_starting_with(query, user))
408 # remove pdcounter stuff
409 book_titles = set(match.pretty_title().lower() for match in result
410 if isinstance(match, models.Book))
411 authors = set(match.name.lower() for match in result
412 if isinstance(match, models.Tag) and match.category=='author')
413 result = tuple(res for res in result if not (
414 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
415 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
418 exact_matches = tuple(res for res in result if res.name.lower() == query)
422 return tuple(result)[:1]
426 tags = request.GET.get('tags', '')
427 prefix = request.GET.get('q', '')
430 tag_list = models.Tag.get_tag_list(tags)
435 result = find_best_matches(prefix, request.user)
437 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
438 context_instance=RequestContext(request))
441 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
442 elif len(result) > 1:
443 return render_to_response('catalogue/search_multiple_hits.html',
444 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
445 context_instance=RequestContext(request))
447 form = PublishingSuggestForm(initial={"books": prefix + ", "})
448 return render_to_response('catalogue/search_no_hits.html',
449 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
450 context_instance=RequestContext(request))
453 def tags_starting_with(request):
454 prefix = request.GET.get('q', '')
455 # Prefix must have at least 2 characters
457 return HttpResponse('')
460 for tag in _tags_starting_with(prefix, request.user):
461 if not tag.name in tags_list:
462 result += "\n" + tag.name
463 tags_list.append(tag.name)
464 return HttpResponse(result)
466 def json_tags_starting_with(request, callback=None):
468 prefix = request.GET.get('q', '')
469 callback = request.GET.get('callback', '')
470 # Prefix must have at least 2 characters
472 return HttpResponse('')
474 for tag in _tags_starting_with(prefix, request.user):
475 if not tag.name in tags_list:
476 tags_list.append(tag.name)
477 if request.GET.get('mozhint', ''):
478 result = [prefix, tags_list]
480 result = {"matches": tags_list}
481 return JSONResponse(result, callback)
483 # ====================
484 # = Shelf management =
485 # ====================
488 def user_shelves(request):
489 shelves = models.Tag.objects.filter(category='set', user=request.user)
490 new_set_form = forms.NewSetForm()
491 return render_to_response('catalogue/user_shelves.html', locals(),
492 context_instance=RequestContext(request))
495 def book_sets(request, slug):
496 if not request.user.is_authenticated():
497 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
499 book = get_object_or_404(models.Book, slug=slug)
500 user_sets = models.Tag.objects.filter(category='set', user=request.user)
501 book_sets = book.tags.filter(category='set', user=request.user)
503 if request.method == 'POST':
504 form = forms.ObjectSetsForm(book, request.user, request.POST)
506 old_shelves = list(book.tags.filter(category='set'))
507 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
509 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
510 shelf.book_count = None
513 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
514 shelf.book_count = None
517 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
518 if request.is_ajax():
519 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
521 return HttpResponseRedirect('/')
523 form = forms.ObjectSetsForm(book, request.user)
524 new_set_form = forms.NewSetForm()
526 return render_to_response('catalogue/book_sets.html', locals(),
527 context_instance=RequestContext(request))
533 def remove_from_shelf(request, shelf, book):
534 book = get_object_or_404(models.Book, slug=book)
535 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
537 if shelf in book.tags:
538 models.Tag.objects.remove_tag(book, shelf)
540 shelf.book_count = None
543 return HttpResponse(_('Book was successfully removed from the shelf'))
545 return HttpResponse(_('This book is not on the shelf'))
548 def collect_books(books):
550 Returns all real books in collection.
554 if len(book.children.all()) == 0:
557 result += collect_books(book.children.all())
562 def download_shelf(request, slug):
564 Create a ZIP archive on disk and transmit it in chunks of 8KB,
565 without loading the whole file into memory. A similar approach can
566 be used for large dynamic PDF files.
568 from slughifi import slughifi
572 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
575 form = forms.DownloadFormatsForm(request.GET)
577 formats = form.cleaned_data['formats']
578 if len(formats) == 0:
579 formats = ['pdf', 'epub', 'mobi', 'odt', 'txt']
581 # Create a ZIP archive
582 temp = tempfile.TemporaryFile()
583 archive = zipfile.ZipFile(temp, 'w')
586 for book in collect_books(models.Book.tagged.with_all(shelf)):
587 if 'pdf' in formats and book.pdf_file:
588 filename = book.pdf_file.path
589 archive.write(filename, str('%s.pdf' % book.slug))
590 if 'mobi' in formats and book.mobi_file:
591 filename = book.mobi_file.path
592 archive.write(filename, str('%s.mobi' % book.slug))
593 if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
594 filename = book.root_ancestor.epub_file.path
595 archive.write(filename, str('%s.epub' % book.root_ancestor.slug))
596 already.add(book.root_ancestor)
597 if 'odt' in formats and book.has_media("odt"):
598 for file in book.get_media("odt"):
599 filename = file.file.path
600 archive.write(filename, str('%s.odt' % slughifi(file.name)))
601 if 'txt' in formats and book.txt_file:
602 filename = book.txt_file.path
603 archive.write(filename, str('%s.txt' % book.slug))
606 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
607 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
608 response['Content-Length'] = temp.tell()
611 response.write(temp.read())
616 def shelf_book_formats(request, shelf):
618 Returns a list of formats of books in shelf.
620 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
622 formats = {'pdf': False, 'epub': False, 'mobi': False, 'odt': False, 'txt': False}
624 for book in collect_books(models.Book.tagged.with_all(shelf)):
626 formats['pdf'] = True
627 if book.root_ancestor.epub_file:
628 formats['epub'] = True
630 formats['mobi'] = True
632 formats['txt'] = True
633 for format in ('odt',):
634 if book.has_media(format):
635 formats[format] = True
637 return HttpResponse(LazyEncoder().encode(formats))
643 def new_set(request):
644 new_set_form = forms.NewSetForm(request.POST)
645 if new_set_form.is_valid():
646 new_set = new_set_form.save(request.user)
648 if request.is_ajax():
649 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
651 return HttpResponseRedirect('/')
653 return HttpResponseRedirect('/')
659 def delete_shelf(request, slug):
660 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
663 if request.is_ajax():
664 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
666 return HttpResponseRedirect('/')
675 form = AuthenticationForm(data=request.POST, prefix='login')
677 auth.login(request, form.get_user())
678 response_data = {'success': True, 'errors': {}}
680 response_data = {'success': False, 'errors': form.errors}
681 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
686 def register(request):
687 registration_form = UserCreationForm(request.POST, prefix='registration')
688 if registration_form.is_valid():
689 user = registration_form.save()
690 user = auth.authenticate(
691 username=registration_form.cleaned_data['username'],
692 password=registration_form.cleaned_data['password1']
694 auth.login(request, user)
695 response_data = {'success': True, 'errors': {}}
697 response_data = {'success': False, 'errors': registration_form.errors}
698 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
702 def logout_then_redirect(request):
704 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
713 def import_book(request):
714 """docstring for import_book"""
715 book_import_form = forms.BookImportForm(request.POST, request.FILES)
716 if book_import_form.is_valid():
718 book_import_form.save()
723 info = sys.exc_info()
724 exception = pprint.pformat(info[1])
725 tb = '\n'.join(traceback.format_tb(info[2]))
726 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
727 return HttpResponse(_("Book imported successfully"))
729 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
734 """ Provides server time for jquery.countdown,
735 in a format suitable for Date.parse()
737 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
742 def book_info(request, id, lang='pl'):
743 book = get_object_or_404(models.Book, id=id)
744 # set language by hand
745 translation.activate(lang)
746 return render_to_response('catalogue/book_info.html', locals(),
747 context_instance=RequestContext(request))
750 def tag_info(request, id):
751 tag = get_object_or_404(models.Tag, id=id)
752 return HttpResponse(tag.description)
755 def download_zip(request, format, slug):
757 if format in ('pdf', 'epub', 'mobi'):
758 url = models.Book.zip_format(format)
759 elif format == 'audiobook' and slug is not None:
760 book = models.Book.objects.get(slug=slug)
761 url = book.zip_audiobooks()
763 raise Http404('No format specified for zip package')
764 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))