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, async_build_pdf
30 from catalogue.tasks import touch_tag
31 from pdcounter import models as pdcounter_models
32 from pdcounter import views as pdcounter_views
33 from suggest.forms import PublishingSuggestForm
34 from picture.models import Picture
36 from itertools import chain
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 = Picture.tagged.with_all(tags)|objects
178 template_name='catalogue/tagged_object_list.html',
180 'categories': categories,
181 'only_shelf': only_shelf,
182 'only_author': only_author,
183 'only_my_shelf': only_my_shelf,
184 'formats_form': forms.DownloadFormatsForm(),
190 def book_fragments(request, book, theme_slug):
191 kwargs = models.Book.split_urlid(book)
194 book = get_object_or_404(models.Book, **kwargs)
196 book_tag = book.book_tag()
197 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
198 fragments = models.Fragment.tagged.with_all([book_tag, theme])
200 return render_to_response('catalogue/book_fragments.html', locals(),
201 context_instance=RequestContext(request))
204 def book_detail(request, book):
205 kwargs = models.Book.split_urlid(book)
209 book = models.Book.objects.get(**kwargs)
210 except models.Book.DoesNotExist:
211 return pdcounter_views.book_stub_detail(request, kwargs['slug'])
213 book_tag = book.book_tag()
214 tags = list(book.tags.filter(~Q(category='set')))
215 categories = split_tags(tags)
216 book_children = book.children.all().order_by('parent_number', 'sort_key')
221 parents.append(_book.parent)
223 parents = reversed(parents)
225 theme_counter = book.theme_counter
226 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
227 for tag in book_themes:
228 tag.count = theme_counter[tag.pk]
230 extra_info = book.get_extra_info_value()
231 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
234 for m in book.media.filter(type='mp3'):
235 # ogg files are always from the same project
236 meta = m.get_extra_info_value()
237 project = meta.get('project')
240 project = u'CzytamySłuchając'
242 projects.add((project, meta.get('funded_by', '')))
243 projects = sorted(projects)
245 custom_pdf_form = forms.CustomPDFForm()
246 return render_to_response('catalogue/book_detail.html', locals(),
247 context_instance=RequestContext(request))
250 def book_text(request, book):
251 kwargs = models.Book.split_fileid(book)
254 book = get_object_or_404(models.Book, **kwargs)
256 if not book.has_html_file():
259 for fragment in book.fragments.all():
260 for theme in fragment.tags.filter(category='theme'):
261 book_themes.setdefault(theme, []).append(fragment)
263 book_themes = book_themes.items()
264 book_themes.sort(key=lambda s: s[0].sort_key)
265 return render_to_response('catalogue/book_text.html', locals(),
266 context_instance=RequestContext(request))
273 def _no_diacritics_regexp(query):
274 """ returns a regexp for searching for a query without diacritics
276 should be locale-aware """
278 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źżŹŻ',
279 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
283 return u"(%s)" % '|'.join(names[l])
284 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
286 def unicode_re_escape(query):
287 """ Unicode-friendly version of re.escape """
288 return re.sub('(?u)(\W)', r'\\\1', query)
290 def _word_starts_with(name, prefix):
291 """returns a Q object getting models having `name` contain a word
292 starting with `prefix`
294 We define word characters as alphanumeric and underscore, like in JS.
296 Works for MySQL, PostgreSQL, Oracle.
297 For SQLite, _sqlite* version is substituted for this.
301 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
302 # can't use [[:<:]] (word start),
303 # but we want both `xy` and `(xy` to catch `(xyz)`
304 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
309 def _word_starts_with_regexp(prefix):
310 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
311 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
314 def _sqlite_word_starts_with(name, prefix):
315 """ version of _word_starts_with for SQLite
317 SQLite in Django uses Python re module
320 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
324 if hasattr(settings, 'DATABASES'):
325 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
326 _word_starts_with = _sqlite_word_starts_with
327 elif settings.DATABASE_ENGINE == 'sqlite3':
328 _word_starts_with = _sqlite_word_starts_with
332 def __init__(self, name, view):
335 self.lower = name.lower()
336 self.category = 'application'
338 return reverse(*self._view)
341 App(u'Leśmianator', (u'lesmianator', )),
345 def _tags_starting_with(prefix, user=None):
346 prefix = prefix.lower()
348 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
349 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
351 books = models.Book.objects.filter(_word_starts_with('title', prefix))
352 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
353 if user and user.is_authenticated():
354 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
356 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
358 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
359 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
362 def _get_result_link(match, tag_list):
363 if isinstance(match, models.Tag):
364 return reverse('catalogue.views.tagged_object_list',
365 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
367 elif isinstance(match, App):
370 return match.get_absolute_url()
373 def _get_result_type(match):
374 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
377 type = match.category
381 def books_starting_with(prefix):
382 prefix = prefix.lower()
383 return models.Book.objects.filter(_word_starts_with('title', prefix))
386 def find_best_matches(query, user=None):
387 """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
390 - zero elements when nothing is found,
391 - one element when a best result is found,
392 - more then one element on multiple exact matches
394 Raises a ValueError on too short a query.
397 query = query.lower()
399 raise ValueError("query must have at least two characters")
401 result = tuple(_tags_starting_with(query, user))
402 # remove pdcounter stuff
403 book_titles = set(match.pretty_title().lower() for match in result
404 if isinstance(match, models.Book))
405 authors = set(match.name.lower() for match in result
406 if isinstance(match, models.Tag) and match.category=='author')
407 result = tuple(res for res in result if not (
408 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
409 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
412 exact_matches = tuple(res for res in result if res.name.lower() == query)
416 return tuple(result)[:1]
420 tags = request.GET.get('tags', '')
421 prefix = request.GET.get('q', '')
424 tag_list = models.Tag.get_tag_list(tags)
429 result = find_best_matches(prefix, request.user)
431 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
432 context_instance=RequestContext(request))
435 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
436 elif len(result) > 1:
437 return render_to_response('catalogue/search_multiple_hits.html',
438 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
439 context_instance=RequestContext(request))
441 form = PublishingSuggestForm(initial={"books": prefix + ", "})
442 return render_to_response('catalogue/search_no_hits.html',
443 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
444 context_instance=RequestContext(request))
447 def tags_starting_with(request):
448 prefix = request.GET.get('q', '')
449 # Prefix must have at least 2 characters
451 return HttpResponse('')
454 for tag in _tags_starting_with(prefix, request.user):
455 if not tag.name in tags_list:
456 result += "\n" + tag.name
457 tags_list.append(tag.name)
458 return HttpResponse(result)
460 def json_tags_starting_with(request, callback=None):
462 prefix = request.GET.get('q', '')
463 callback = request.GET.get('callback', '')
464 # Prefix must have at least 2 characters
466 return HttpResponse('')
468 for tag in _tags_starting_with(prefix, request.user):
469 if not tag.name in tags_list:
470 tags_list.append(tag.name)
471 if request.GET.get('mozhint', ''):
472 result = [prefix, tags_list]
474 result = {"matches": tags_list}
475 return JSONResponse(result, callback)
477 # ====================
478 # = Shelf management =
479 # ====================
482 def user_shelves(request):
483 shelves = models.Tag.objects.filter(category='set', user=request.user)
484 new_set_form = forms.NewSetForm()
485 return render_to_response('catalogue/user_shelves.html', locals(),
486 context_instance=RequestContext(request))
489 def book_sets(request, book):
490 if not request.user.is_authenticated():
491 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
493 kwargs = models.Book.split_urlid(book)
496 book = get_object_or_404(models.Book, **kwargs)
498 user_sets = models.Tag.objects.filter(category='set', user=request.user)
499 book_sets = book.tags.filter(category='set', user=request.user)
501 if request.method == 'POST':
502 form = forms.ObjectSetsForm(book, request.user, request.POST)
504 old_shelves = list(book.tags.filter(category='set'))
505 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
507 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
510 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
513 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
514 if request.is_ajax():
515 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
517 return HttpResponseRedirect('/')
519 form = forms.ObjectSetsForm(book, request.user)
520 new_set_form = forms.NewSetForm()
522 return render_to_response('catalogue/book_sets.html', locals(),
523 context_instance=RequestContext(request))
529 def remove_from_shelf(request, shelf, book):
530 kwargs = models.Book.split_urlid(book)
533 book = get_object_or_404(models.Book, **kwargs)
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)
541 return HttpResponse(_('Book was successfully removed from the shelf'))
543 return HttpResponse(_('This book is not on the shelf'))
546 def collect_books(books):
548 Returns all real books in collection.
552 if len(book.children.all()) == 0:
555 result += collect_books(book.children.all())
560 def download_shelf(request, slug):
562 Create a ZIP archive on disk and transmit it in chunks of 8KB,
563 without loading the whole file into memory. A similar approach can
564 be used for large dynamic PDF files.
566 from slughifi import slughifi
570 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
573 form = forms.DownloadFormatsForm(request.GET)
575 formats = form.cleaned_data['formats']
576 if len(formats) == 0:
577 formats = models.Book.ebook_formats
579 # Create a ZIP archive
580 temp = tempfile.TemporaryFile()
581 archive = zipfile.ZipFile(temp, 'w')
583 for book in collect_books(models.Book.tagged.with_all(shelf)):
584 fileid = book.fileid()
585 for ebook_format in models.Book.ebook_formats:
586 if ebook_format in formats and book.has_media(ebook_format):
587 filename = book.get_media(ebook_format).path
588 archive.write(filename, str('%s.%s' % (fileid, ebook_format)))
591 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
592 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
593 response['Content-Length'] = temp.tell()
596 response.write(temp.read())
601 def shelf_book_formats(request, shelf):
603 Returns a list of formats of books in shelf.
605 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
608 for ebook_format in models.Book.ebook_formats:
609 formats[ebook_format] = False
611 for book in collect_books(models.Book.tagged.with_all(shelf)):
612 for ebook_format in models.Book.ebook_formats:
613 if book.has_media(ebook_format):
614 formats[ebook_format] = True
616 return HttpResponse(LazyEncoder().encode(formats))
622 def new_set(request):
623 new_set_form = forms.NewSetForm(request.POST)
624 if new_set_form.is_valid():
625 new_set = new_set_form.save(request.user)
627 if request.is_ajax():
628 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
630 return HttpResponseRedirect('/')
632 return HttpResponseRedirect('/')
638 def delete_shelf(request, slug):
639 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
642 if request.is_ajax():
643 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
645 return HttpResponseRedirect('/')
653 def import_book(request):
654 """docstring for import_book"""
655 book_import_form = forms.BookImportForm(request.POST, request.FILES)
656 if book_import_form.is_valid():
658 book_import_form.save()
663 info = sys.exc_info()
664 exception = pprint.pformat(info[1])
665 tb = '\n'.join(traceback.format_tb(info[2]))
666 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
667 return HttpResponse(_("Book imported successfully"))
669 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
674 def book_info(request, id, lang='pl'):
675 book = get_object_or_404(models.Book, id=id)
676 # set language by hand
677 translation.activate(lang)
678 return render_to_response('catalogue/book_info.html', locals(),
679 context_instance=RequestContext(request))
682 def tag_info(request, id):
683 tag = get_object_or_404(models.Tag, id=id)
684 return HttpResponse(tag.description)
687 def download_zip(request, format, book=None):
688 kwargs = models.Book.split_fileid(book)
691 if format in models.Book.ebook_formats:
692 url = models.Book.zip_format(format)
693 elif format == 'audiobook' and kwargs is not None:
694 book = get_object_or_404(models.Book, **kwargs)
695 url = book.zip_audiobooks()
697 raise Http404('No format specified for zip package')
698 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
701 def download_custom_pdf(request, book_fileid):
702 kwargs = models.Book.split_fileid(book_fileid)
705 book = get_object_or_404(models.Book, **kwargs)
707 if request.method == 'GET':
708 form = forms.CustomPDFForm(request.GET)
710 cust = form.customizations
711 pdf_file = models.get_customized_pdf_path(book, cust)
713 if not path.exists(pdf_file):
714 result = async_build_pdf.delay(book.id, cust, pdf_file)
716 return AttachmentHttpResponse(file_name=("%s.pdf" % book_fileid), file_path=pdf_file, mimetype="application/pdf")
718 raise Http404(_('Incorrect customization options for PDF'))
720 raise Http404(_('Bad method'))