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.
6 from django.http import Http404, HttpResponse
7 from rest_framework.generics import ListAPIView, RetrieveAPIView, get_object_or_404
8 from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
9 from rest_framework.response import Response
10 from rest_framework import status
11 from paypal.permissions import IsSubscribed
12 from api.handlers import read_tags
13 from .helpers import books_after, order_books
14 from . import serializers
15 from catalogue.forms import BookImportForm
16 from catalogue.models import Book, Collection, Tag, Fragment
17 from catalogue.models.tag import prefetch_relations
18 from wolnelektury.utils import re_escape
21 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
24 class CollectionList(ListAPIView):
25 queryset = Collection.objects.all()
26 serializer_class = serializers.CollectionListSerializer
29 class CollectionDetail(RetrieveAPIView):
30 queryset = Collection.objects.all()
32 serializer_class = serializers.CollectionSerializer
35 class BookList(ListAPIView):
36 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
37 queryset = Book.objects.none() # Required for DjangoModelPermissions
38 serializer_class = serializers.BookListSerializer
40 def get_queryset(self):
42 tags, ancestors = read_tags(
43 self.kwargs.get('tags', ''), self.request,
44 allowed=('author', 'epoch', 'kind', 'genre')
49 new_api = self.request.query_params.get('new_api')
50 after = self.request.query_params.get('after', self.kwargs.get('after'))
51 count = self.request.query_params.get('count', self.kwargs.get('count'))
54 if self.kwargs.get('top_level'):
55 books = Book.tagged_top_level(tags)
60 books = Book.tagged.with_all(tags)
62 books = Book.objects.all()
63 books = order_books(books, new_api)
65 if self.kwargs.get('top_level'):
66 books = books.filter(parent=None)
67 if self.kwargs.get('audiobooks'):
68 books = books.filter(media__type='mp3').distinct()
69 if self.kwargs.get('daisy'):
70 books = books.filter(media__type='daisy').distinct()
71 if self.kwargs.get('recommended'):
72 books = books.filter(recommended=True)
73 if self.kwargs.get('newest'):
74 books = books.order_by('-created_at')
77 books = books_after(books, after, new_api)
79 prefetch_relations(books, 'author')
80 prefetch_relations(books, 'genre')
81 prefetch_relations(books, 'kind')
82 prefetch_relations(books, 'epoch')
89 def post(self, request, **kwargs):
91 data = json.loads(request.POST.get('data'))
92 form = BookImportForm(data)
95 return Response({}, status=status.HTTP_201_CREATED)
100 class BookDetail(RetrieveAPIView):
101 queryset = Book.objects.all()
102 lookup_field = 'slug'
103 serializer_class = serializers.BookDetailSerializer
106 class EbookList(BookList):
107 serializer_class = serializers.EbookSerializer
110 class Preview(ListAPIView):
111 queryset = Book.objects.filter(preview=True)
112 serializer_class = serializers.BookPreviewSerializer
115 class FilterBookList(ListAPIView):
116 serializer_class = serializers.FilterBookListSerializer
118 def parse_bool(self, s):
119 if s in ('true', 'false'):
124 def get_queryset(self):
126 search_string = self.request.query_params.get('search')
127 is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
128 is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
129 preview = self.parse_bool(self.request.query_params.get('preview'))
131 new_api = self.request.query_params.get('new_api')
132 after = self.request.query_params.get('after')
133 count = int(self.request.query_params.get('count', 50))
134 books = order_books(Book.objects.distinct(), new_api)
135 if is_lektura is not None:
136 books = books.filter(has_audience=is_lektura)
137 if is_audiobook is not None:
139 books = books.filter(media__type='mp3')
141 books = books.exclude(media__type='mp3')
142 if preview is not None:
143 books = books.filter(preview=preview)
144 for category in book_tag_categories:
145 category_plural = category + 's'
146 if category_plural in self.request.query_params:
147 slugs = self.request.query_params[category_plural].split(',')
148 tags = Tag.objects.filter(category=category, slug__in=slugs)
149 books = Book.tagged.with_any(tags, books)
150 if (search_string is not None) and len(search_string) < 3:
153 search_string = re_escape(search_string)
154 books_author = books.filter(cached_author__iregex=r'\m' + search_string)
155 books_title = books.filter(title__iregex=r'\m' + search_string)
156 books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
157 if after and (key_sep in after):
158 which, key = after.split(key_sep, 1)
160 book_lists = [(books_after(books_title, key, new_api), 'title')]
161 else: # which == 'author'
162 book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
164 book_lists = [(books_author, 'author'), (books_title, 'title')]
166 if after and key_sep in after:
167 which, key = after.split(key_sep, 1)
168 books = books_after(books, key, new_api)
169 book_lists = [(books, 'book')]
172 for book_list, label in book_lists:
173 for category in book_tag_categories:
174 book_list = prefetch_relations(book_list, category)
175 remaining_count = count - len(filtered_books)
176 for book in book_list[:remaining_count]:
177 book.key = '%s%s%s' % (
178 label, key_sep, book.slug if not new_api else book.full_sort_key())
179 filtered_books.append(book)
180 if len(filtered_books) == count:
183 return filtered_books
186 class EpubView(RetrieveAPIView):
187 queryset = Book.objects.all()
188 lookup_field = 'slug'
189 permission_classes = [IsSubscribed]
191 def get(self, *args, **kwargs):
192 return HttpResponse(self.get_object().get_media('epub'))
195 class TagCategoryView(ListAPIView):
196 serializer_class = serializers.TagSerializer
198 def get_queryset(self):
199 category = self.kwargs['category']
200 tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
201 if self.request.query_params.get('book_only') == 'true':
202 tags = tags.filter(for_books=True)
203 if self.request.GET.get('picture_only') == 'true':
204 tags = filter(for_pictures=True)
206 after = self.request.query_params.get('after')
207 count = self.request.query_params.get('count')
209 tags = tags.filter(slug__gt=after)
216 class TagView(RetrieveAPIView):
217 serializer_class = serializers.TagDetailSerializer
219 def get_object(self):
220 return get_object_or_404(
222 category=self.kwargs['category'],
223 slug=self.kwargs['slug']
227 class FragmentList(ListAPIView):
228 serializer_class = serializers.FragmentSerializer
230 def get_queryset(self):
232 tags, ancestors = read_tags(
235 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
239 return Fragment.tagged.with_all(tags).select_related('book')
242 class FragmentView(RetrieveAPIView):
243 serializer_class = serializers.FragmentDetailSerializer
245 def get_object(self):
246 return get_object_or_404(
248 book__slug=self.kwargs['book'],
249 anchor=self.kwargs['anchor']