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 api.utils import vary_on_auth
14 from .helpers import books_after, order_books
15 from . import serializers
16 from catalogue.forms import BookImportForm
17 from catalogue.models import Book, Collection, Tag, Fragment
18 from catalogue.models.tag import prefetch_relations
19 from wolnelektury.utils import re_escape
22 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
25 class CollectionList(ListAPIView):
26 queryset = Collection.objects.all()
27 serializer_class = serializers.CollectionListSerializer
30 @vary_on_auth # Because of 'liked'.
31 class CollectionDetail(RetrieveAPIView):
32 queryset = Collection.objects.all()
34 serializer_class = serializers.CollectionSerializer
37 @vary_on_auth # Because of 'liked'.
38 class BookList(ListAPIView):
39 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
40 queryset = Book.objects.none() # Required for DjangoModelPermissions
41 serializer_class = serializers.BookListSerializer
43 def get_queryset(self):
45 tags, ancestors = read_tags(
46 self.kwargs.get('tags', ''), self.request,
47 allowed=('author', 'epoch', 'kind', 'genre')
52 new_api = self.request.query_params.get('new_api')
53 after = self.request.query_params.get('after', self.kwargs.get('after'))
54 count = self.request.query_params.get('count', self.kwargs.get('count'))
57 if self.kwargs.get('top_level'):
58 books = Book.tagged_top_level(tags)
63 books = Book.tagged.with_all(tags)
65 books = Book.objects.all()
66 books = order_books(books, new_api)
68 if self.kwargs.get('top_level'):
69 books = books.filter(parent=None)
70 if self.kwargs.get('audiobooks'):
71 books = books.filter(media__type='mp3').distinct()
72 if self.kwargs.get('daisy'):
73 books = books.filter(media__type='daisy').distinct()
74 if self.kwargs.get('recommended'):
75 books = books.filter(recommended=True)
76 if self.kwargs.get('newest'):
77 books = books.order_by('-created_at')
80 books = books_after(books, after, new_api)
82 prefetch_relations(books, 'author')
83 prefetch_relations(books, 'genre')
84 prefetch_relations(books, 'kind')
85 prefetch_relations(books, 'epoch')
92 def post(self, request, **kwargs):
94 data = json.loads(request.POST.get('data'))
95 form = BookImportForm(data)
98 return Response({}, status=status.HTTP_201_CREATED)
103 @vary_on_auth # Because of 'liked'.
104 class BookDetail(RetrieveAPIView):
105 queryset = Book.objects.all()
106 lookup_field = 'slug'
107 serializer_class = serializers.BookDetailSerializer
110 class EbookList(BookList):
111 serializer_class = serializers.EbookSerializer
114 @vary_on_auth # Because of 'liked'.
115 class Preview(ListAPIView):
116 queryset = Book.objects.filter(preview=True)
117 serializer_class = serializers.BookPreviewSerializer
120 @vary_on_auth # Because of 'liked'.
121 class FilterBookList(ListAPIView):
122 serializer_class = serializers.FilterBookListSerializer
124 def parse_bool(self, s):
125 if s in ('true', 'false'):
130 def get_queryset(self):
132 search_string = self.request.query_params.get('search')
133 is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
134 is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
135 preview = self.parse_bool(self.request.query_params.get('preview'))
137 new_api = self.request.query_params.get('new_api')
138 after = self.request.query_params.get('after')
139 count = int(self.request.query_params.get('count', 50))
140 books = order_books(Book.objects.distinct(), new_api)
141 if is_lektura is not None:
142 books = books.filter(has_audience=is_lektura)
143 if is_audiobook is not None:
145 books = books.filter(media__type='mp3')
147 books = books.exclude(media__type='mp3')
148 if preview is not None:
149 books = books.filter(preview=preview)
150 for category in book_tag_categories:
151 category_plural = category + 's'
152 if category_plural in self.request.query_params:
153 slugs = self.request.query_params[category_plural].split(',')
154 tags = Tag.objects.filter(category=category, slug__in=slugs)
155 books = Book.tagged.with_any(tags, books)
156 if (search_string is not None) and len(search_string) < 3:
159 search_string = re_escape(search_string)
160 books_author = books.filter(cached_author__iregex=r'\m' + search_string)
161 books_title = books.filter(title__iregex=r'\m' + search_string)
162 books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
163 if after and (key_sep in after):
164 which, key = after.split(key_sep, 1)
166 book_lists = [(books_after(books_title, key, new_api), 'title')]
167 else: # which == 'author'
168 book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
170 book_lists = [(books_author, 'author'), (books_title, 'title')]
172 if after and key_sep in after:
173 which, key = after.split(key_sep, 1)
174 books = books_after(books, key, new_api)
175 book_lists = [(books, 'book')]
178 for book_list, label in book_lists:
179 for category in book_tag_categories:
180 book_list = prefetch_relations(book_list, category)
181 remaining_count = count - len(filtered_books)
182 for book in book_list[:remaining_count]:
183 book.key = '%s%s%s' % (
184 label, key_sep, book.slug if not new_api else book.full_sort_key())
185 filtered_books.append(book)
186 if len(filtered_books) == count:
189 return filtered_books
192 class EpubView(RetrieveAPIView):
193 queryset = Book.objects.all()
194 lookup_field = 'slug'
195 permission_classes = [IsSubscribed]
197 def get(self, *args, **kwargs):
198 return HttpResponse(self.get_object().get_media('epub'))
201 class TagCategoryView(ListAPIView):
202 serializer_class = serializers.TagSerializer
204 def get_queryset(self):
205 category = self.kwargs['category']
206 tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
207 if self.request.query_params.get('book_only') == 'true':
208 tags = tags.filter(for_books=True)
209 if self.request.GET.get('picture_only') == 'true':
210 tags = filter(for_pictures=True)
212 after = self.request.query_params.get('after')
213 count = self.request.query_params.get('count')
215 tags = tags.filter(slug__gt=after)
222 class TagView(RetrieveAPIView):
223 serializer_class = serializers.TagDetailSerializer
225 def get_object(self):
226 return get_object_or_404(
228 category=self.kwargs['category'],
229 slug=self.kwargs['slug']
233 @vary_on_auth # Because of 'liked'.
234 class FragmentList(ListAPIView):
235 serializer_class = serializers.FragmentSerializer
237 def get_queryset(self):
239 tags, ancestors = read_tags(
242 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
246 return Fragment.tagged.with_all(tags).select_related('book')
249 @vary_on_auth # Because of 'liked'.
250 class FragmentView(RetrieveAPIView):
251 serializer_class = serializers.FragmentDetailSerializer
253 def get_object(self):
254 return get_object_or_404(
256 book__slug=self.kwargs['book'],
257 anchor=self.kwargs['anchor']