+ def cover(cls, book):
+ return MEDIA_BASE + book.cover.url if book.cover else ''
+
+ @classmethod
+ def cover_thumb(cls, book):
+ return MEDIA_BASE + default.backend.get_thumbnail(
+ book.cover, "139x193").url if book.cover else ''
+
+
+
+class BookDetailHandler(BaseHandler, BookDetails):
+ """ Main handler for Book objects.
+
+ Responsible for single Book details.
+ """
+ allowed_methods = ['GET']
+ fields = ['title', 'parent', 'children'] + Book.formats + [
+ 'media', 'url', 'cover', 'cover_thumb'] + [
+ category_plural[c] for c in book_tag_categories]
+
+ @piwik_track
+ def read(self, request, book):
+ """ Returns details of a book, identified by a slug and lang. """
+ try:
+ return Book.objects.get(slug=book)
+ except Book.DoesNotExist:
+ return rc.NOT_FOUND
+
+
+class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
+ """ Main handler for Book objects.
+
+ Responsible for lists of Book objects.
+ """
+ allowed_methods = ('GET',)
+ model = Book
+ fields = book_tag_categories + ['href', 'title', 'url', 'cover', 'cover_thumb']
+
+ @classmethod
+ def genres(cls, book):
+ """ Returns all media for a book. """
+ return book.tags.filter(category='genre')
+
+ @piwik_track
+ def read(self, request, tags=None, top_level=False,
+ audiobooks=False, daisy=False, pk=None):
+ """ Lists all books with given tags.
+
+ :param tags: filtering tags; should be a path of categories
+ and slugs, i.e.: authors/an-author/epoch/an-epoch/
+ :param top_level: if True and a book is included in the results,
+ it's children are aren't. By default all books matching the tags
+ are returned.
+ """
+ if pk is not None:
+ try:
+ return Book.objects.get(pk=pk)
+ except Book.DoesNotExist:
+ return rc.NOT_FOUND
+
+ try:
+ tags, _ancestors = read_tags(tags, allowed=book_tag_categories)
+ except ValueError:
+ return rc.NOT_FOUND
+
+ if tags:
+ if top_level:
+ books = Book.tagged_top_level(tags)
+ return books if books else rc.NOT_FOUND
+ else:
+ books = Book.tagged.with_all(tags)
+ else:
+ books = Book.objects.all()
+
+ if top_level:
+ books = books.filter(parent=None)
+ if audiobooks:
+ books = books.filter(media__type='mp3').distinct()
+ if daisy:
+ books = books.filter(media__type='daisy').distinct()
+
+ if books.exists():
+ return books
+ else:
+ return rc.NOT_FOUND
+
+ def create(self, request, *args, **kwargs):
+ return rc.FORBIDDEN
+
+
+class BooksHandler(BookDetailHandler):
+ allowed_methods = ('GET', 'POST')
+ model = Book
+ fields = book_tag_categories + ['href', 'title', 'url', 'cover', 'cover_thumb']
+ anonymous = AnonymousBooksHandler
+
+ def create(self, request, *args, **kwargs):
+ if not request.user.has_perm('catalogue.add_book'):
+ return rc.FORBIDDEN
+
+ data = json.loads(request.POST.get('data'))
+ form = BookImportForm(data)
+ if form.is_valid():
+ form.save()
+ return rc.CREATED
+ else:
+ return rc.NOT_FOUND