1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django.http import Http404, HttpResponse
6 from rest_framework.generics import ListAPIView, RetrieveAPIView, get_object_or_404
7 from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
8 from rest_framework.response import Response
9 from rest_framework import status
10 from api.handlers import read_tags
11 from api.utils import vary_on_auth
12 from .helpers import books_after, order_books
13 from . import serializers
14 from catalogue.forms import BookImportForm
15 from catalogue.models import Book, Collection, Tag, Fragment, BookMedia
16 from catalogue.models.tag import prefetch_relations
17 from club.permissions import IsClubMember
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 @vary_on_auth # Because of 'liked'.
30 class CollectionDetail(RetrieveAPIView):
31 queryset = Collection.objects.all()
33 serializer_class = serializers.CollectionSerializer
36 @vary_on_auth # Because of 'liked'.
37 class BookList(ListAPIView):
38 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
39 queryset = Book.objects.none() # Required for DjangoModelPermissions
40 serializer_class = serializers.BookListSerializer
42 def get_queryset(self):
44 tags, ancestors = read_tags(
45 self.kwargs.get('tags', ''), self.request,
46 allowed=('author', 'epoch', 'kind', 'genre')
51 new_api = self.request.query_params.get('new_api')
52 after = self.request.query_params.get('after', self.kwargs.get('after'))
53 count = self.request.query_params.get('count', self.kwargs.get('count'))
61 if self.kwargs.get('top_level'):
62 books = Book.tagged_top_level(tags)
67 books = Book.tagged.with_all(tags)
69 books = Book.objects.all()
70 books = order_books(books, new_api)
72 if self.kwargs.get('top_level'):
73 books = books.filter(parent=None)
74 if self.kwargs.get('audiobooks'):
75 books = books.filter(media__type='mp3').distinct()
76 if self.kwargs.get('daisy'):
77 books = books.filter(media__type='daisy').distinct()
78 if self.kwargs.get('recommended'):
79 books = books.filter(recommended=True)
80 if self.kwargs.get('newest'):
81 books = books.order_by('-created_at')
84 books = books_after(books, after, new_api)
86 prefetch_relations(books, 'author')
87 prefetch_relations(books, 'genre')
88 prefetch_relations(books, 'kind')
89 prefetch_relations(books, 'epoch')
96 def post(self, request, **kwargs):
97 if kwargs.get('audiobooks'):
98 return self.post_audiobook(request, **kwargs)
100 return self.post_book(request, **kwargs)
102 def post_book(self, request, **kwargs):
103 data = json.loads(request.POST.get('data'))
104 form = BookImportForm(data)
107 return Response({}, status=status.HTTP_201_CREATED)
111 def post_audiobook(self, request, **kwargs):
112 index = int(request.POST['part_index'])
113 parts_count = int(request.POST['parts_count'])
114 media_type = request.POST['type'].lower()
115 source_sha1 = request.POST.get('source_sha1')
116 name = request.POST.get('name', '')
117 part_name = request.POST.get('part_name', '')
119 _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
120 book = Book.objects.get(slug=slug)
124 bm = book.media.get(type=media_type, source_sha1=source_sha1)
125 except (AssertionError, BookMedia.DoesNotExist):
126 bm = BookMedia(book=book, type=media_type)
128 bm.part_name = part_name
130 bm.file.save(None, request.data['file'], save=False)
131 bm.save(parts_count=parts_count)
133 return Response({}, status=status.HTTP_201_CREATED)
136 @vary_on_auth # Because of 'liked'.
137 class BookDetail(RetrieveAPIView):
138 queryset = Book.objects.all()
139 lookup_field = 'slug'
140 serializer_class = serializers.BookDetailSerializer
143 class EbookList(BookList):
144 serializer_class = serializers.EbookSerializer
147 @vary_on_auth # Because of 'liked'.
148 class Preview(ListAPIView):
149 queryset = Book.objects.filter(preview=True)
150 serializer_class = serializers.BookPreviewSerializer
153 @vary_on_auth # Because of 'liked'.
154 class FilterBookList(ListAPIView):
155 serializer_class = serializers.FilterBookListSerializer
157 def parse_bool(self, s):
158 if s in ('true', 'false'):
163 def get_queryset(self):
165 search_string = self.request.query_params.get('search')
166 is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
167 is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
168 preview = self.parse_bool(self.request.query_params.get('preview'))
170 new_api = self.request.query_params.get('new_api')
171 after = self.request.query_params.get('after')
172 count = int(self.request.query_params.get('count', 50))
173 books = order_books(Book.objects.distinct(), new_api)
174 if is_lektura is not None:
175 books = books.filter(has_audience=is_lektura)
176 if is_audiobook is not None:
178 books = books.filter(media__type='mp3')
180 books = books.exclude(media__type='mp3')
181 if preview is not None:
182 books = books.filter(preview=preview)
183 for category in book_tag_categories:
184 category_plural = category + 's'
185 if category_plural in self.request.query_params:
186 slugs = self.request.query_params[category_plural].split(',')
187 tags = Tag.objects.filter(category=category, slug__in=slugs)
188 books = Book.tagged.with_any(tags, books)
189 if (search_string is not None) and len(search_string) < 3:
192 search_string = re_escape(search_string)
193 books_author = books.filter(cached_author__iregex=r'\m' + search_string)
194 books_title = books.filter(title__iregex=r'\m' + search_string)
195 books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
196 if after and (key_sep in after):
197 which, key = after.split(key_sep, 1)
199 book_lists = [(books_after(books_title, key, new_api), 'title')]
200 else: # which == 'author'
201 book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
203 book_lists = [(books_author, 'author'), (books_title, 'title')]
205 if after and key_sep in after:
206 which, key = after.split(key_sep, 1)
207 books = books_after(books, key, new_api)
208 book_lists = [(books, 'book')]
211 for book_list, label in book_lists:
212 for category in book_tag_categories:
213 book_list = prefetch_relations(book_list, category)
214 remaining_count = count - len(filtered_books)
215 for book in book_list[:remaining_count]:
216 book.key = '%s%s%s' % (
217 label, key_sep, book.slug if not new_api else book.full_sort_key())
218 filtered_books.append(book)
219 if len(filtered_books) == count:
222 return filtered_books
225 class EpubView(RetrieveAPIView):
226 queryset = Book.objects.all()
227 lookup_field = 'slug'
228 permission_classes = [IsClubMember]
230 def get(self, *args, **kwargs):
231 return HttpResponse(self.get_object().get_media('epub'))
234 class TagCategoryView(ListAPIView):
235 serializer_class = serializers.TagSerializer
237 def get_queryset(self):
238 category = self.kwargs['category']
239 tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
240 if self.request.query_params.get('book_only') == 'true':
241 tags = tags.filter(for_books=True)
242 if self.request.GET.get('picture_only') == 'true':
243 tags = filter(for_pictures=True)
245 after = self.request.query_params.get('after')
246 count = self.request.query_params.get('count')
248 tags = tags.filter(slug__gt=after)
255 class TagView(RetrieveAPIView):
256 serializer_class = serializers.TagDetailSerializer
258 def get_object(self):
259 return get_object_or_404(
261 category=self.kwargs['category'],
262 slug=self.kwargs['slug']
266 @vary_on_auth # Because of 'liked'.
267 class FragmentList(ListAPIView):
268 serializer_class = serializers.FragmentSerializer
270 def get_queryset(self):
272 tags, ancestors = read_tags(
275 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
279 return Fragment.tagged.with_all(tags).select_related('book')
282 @vary_on_auth # Because of 'liked'.
283 class FragmentView(RetrieveAPIView):
284 serializer_class = serializers.FragmentDetailSerializer
286 def get_object(self):
287 return get_object_or_404(
289 book__slug=self.kwargs['book'],
290 anchor=self.kwargs['anchor']