1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from django.conf import settings
7 from django.http import Http404, HttpResponse
8 from django.utils.decorators import method_decorator
9 from django.views.decorators.cache import never_cache
10 from rest_framework.generics import ListAPIView, RetrieveAPIView, get_object_or_404
11 from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
12 from rest_framework.response import Response
13 from rest_framework import status
14 from api.handlers import read_tags
15 from api.utils import vary_on_auth
16 from catalogue.forms import BookImportForm
17 from catalogue.models import Book, Collection, Tag, Fragment, BookMedia
18 from catalogue.models.tag import prefetch_relations
19 from club.models import Membership
20 from club.permissions import IsClubMember
21 from wolnelektury.utils import re_escape
22 from .helpers import books_after, order_books
23 from . import serializers
26 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
29 class CollectionList(ListAPIView):
30 queryset = Collection.objects.filter(listed=True)
31 serializer_class = serializers.CollectionListSerializer
34 @vary_on_auth # Because of 'liked'.
35 class CollectionDetail(RetrieveAPIView):
36 queryset = Collection.objects.all()
38 serializer_class = serializers.CollectionSerializer
41 @vary_on_auth # Because of 'liked'.
42 class BookList(ListAPIView):
43 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
44 queryset = Book.objects.none() # Required for DjangoModelPermissions
45 serializer_class = serializers.BookListSerializer
47 def get(self, request, filename=None, **kwargs):
48 if filename and not kwargs.get('tags') and 'count' not in request.query_params:
50 with open(os.path.join(settings.MEDIA_ROOT, 'api', '%s.%s' % (filename, request.accepted_renderer.format)), 'rb') as f:
52 return HttpResponse(content, content_type=request.accepted_media_type)
55 return super().get(request, filename=filename, **kwargs)
57 def get_queryset(self):
59 tags, ancestors = read_tags(
60 self.kwargs.get('tags', ''), self.request,
61 allowed=('author', 'epoch', 'kind', 'genre')
66 new_api = self.request.query_params.get('new_api')
67 after = self.request.query_params.get('after', self.kwargs.get('after'))
68 count = self.request.query_params.get('count', self.kwargs.get('count'))
76 if self.kwargs.get('top_level'):
77 books = Book.tagged_top_level(tags)
82 books = Book.tagged.with_all(tags)
84 books = Book.objects.all()
85 books = books.filter(findable=True)
86 books = order_books(books, new_api)
88 if not Membership.is_active_for(self.request.user):
89 books = books.exclude(preview=True)
91 if self.kwargs.get('top_level'):
92 books = books.filter(parent=None)
93 if self.kwargs.get('audiobooks'):
94 books = books.filter(media__type='mp3').distinct()
95 if self.kwargs.get('daisy'):
96 books = books.filter(media__type='daisy').distinct()
97 if self.kwargs.get('recommended'):
98 books = books.filter(recommended=True)
99 if self.kwargs.get('newest'):
100 books = books.order_by('-created_at')
103 books = books_after(books, after, new_api)
105 prefetch_relations(books, 'author')
106 prefetch_relations(books, 'genre')
107 prefetch_relations(books, 'kind')
108 prefetch_relations(books, 'epoch')
111 books = books[:count]
115 def post(self, request, **kwargs):
116 if kwargs.get('audiobooks'):
117 return self.post_audiobook(request, **kwargs)
119 return self.post_book(request, **kwargs)
121 def post_book(self, request, **kwargs):
122 data = json.loads(request.POST.get('data'))
123 form = BookImportForm(data)
126 return Response({}, status=status.HTTP_201_CREATED)
130 def post_audiobook(self, request, **kwargs):
131 index = int(request.POST['part_index'])
132 parts_count = int(request.POST['parts_count'])
133 media_type = request.POST['type'].lower()
134 source_sha1 = request.POST.get('source_sha1')
135 name = request.POST.get('name', '')
136 part_name = request.POST.get('part_name', '')
138 project_description = request.POST.get('project_description', '')
139 project_icon = request.POST.get('project_icon', '')
141 _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
142 book = Book.objects.get(slug=slug)
146 bm = book.media.get(type=media_type, source_sha1=source_sha1)
147 except (AssertionError, BookMedia.DoesNotExist):
148 bm = BookMedia(book=book, type=media_type)
150 bm.part_name = part_name
152 bm.project_description = project_description
153 bm.project_icon = project_icon
154 bm.file.save(None, request.data['file'], save=False)
155 bm.save(parts_count=parts_count)
157 return Response({}, status=status.HTTP_201_CREATED)
160 @vary_on_auth # Because of 'liked'.
161 class BookDetail(RetrieveAPIView):
162 queryset = Book.objects.all()
163 lookup_field = 'slug'
164 serializer_class = serializers.BookDetailSerializer
167 @vary_on_auth # Because of embargo links.
168 class EbookList(BookList):
169 serializer_class = serializers.EbookSerializer
172 @method_decorator(never_cache, name='dispatch')
173 class Preview(ListAPIView):
174 #queryset = Book.objects.filter(preview=True)
175 serializer_class = serializers.BookPreviewSerializer
177 def get_queryset(self):
178 qs = Book.objects.filter(preview=True)
179 # FIXME: temporary workaround for a problem with iOS app; see #3954.
180 if 'Darwin' in self.request.META.get('HTTP_USER_AGENT', '') and 'debug' not in self.request.GET:
185 @vary_on_auth # Because of 'liked'.
186 class FilterBookList(ListAPIView):
187 serializer_class = serializers.FilterBookListSerializer
189 def parse_bool(self, s):
190 if s in ('true', 'false'):
195 def get_queryset(self):
197 search_string = self.request.query_params.get('search')
198 is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
199 is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
200 preview = self.parse_bool(self.request.query_params.get('preview'))
201 if not Membership.is_active_for(self.request.user):
204 new_api = self.request.query_params.get('new_api')
205 after = self.request.query_params.get('after')
206 count = int(self.request.query_params.get('count', 50))
207 books = order_books(Book.objects.distinct(), new_api)
208 books = books.filter(findable=True)
209 if is_lektura is not None:
210 books = books.filter(has_audience=is_lektura)
211 if is_audiobook is not None:
213 books = books.filter(media__type='mp3')
215 books = books.exclude(media__type='mp3')
216 if preview is not None:
217 books = books.filter(preview=preview)
218 for category in book_tag_categories:
219 category_plural = category + 's'
220 if category_plural in self.request.query_params:
221 slugs = self.request.query_params[category_plural].split(',')
222 tags = Tag.objects.filter(category=category, slug__in=slugs)
223 books = Book.tagged.with_any(tags, books)
224 if (search_string is not None) and len(search_string) < 3:
227 search_string = re_escape(search_string)
228 books_author = books.filter(cached_author__iregex=r'\m' + search_string)
229 books_title = books.filter(title__iregex=r'\m' + search_string)
230 books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
231 if after and (key_sep in after):
232 which, key = after.split(key_sep, 1)
234 book_lists = [(books_after(books_title, key, new_api), 'title')]
235 else: # which == 'author'
236 book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
238 book_lists = [(books_author, 'author'), (books_title, 'title')]
240 if after and key_sep in after:
241 which, key = after.split(key_sep, 1)
242 books = books_after(books, key, new_api)
243 book_lists = [(books, 'book')]
246 for book_list, label in book_lists:
247 for category in book_tag_categories:
248 book_list = prefetch_relations(book_list, category)
249 remaining_count = count - len(filtered_books)
250 for book in book_list[:remaining_count]:
251 book.key = '%s%s%s' % (
252 label, key_sep, book.slug if not new_api else book.full_sort_key())
253 filtered_books.append(book)
254 if len(filtered_books) == count:
257 return filtered_books
260 class EpubView(RetrieveAPIView):
261 queryset = Book.objects.all()
262 lookup_field = 'slug'
263 permission_classes = [IsClubMember]
265 @method_decorator(never_cache)
266 def get(self, *args, **kwargs):
267 return HttpResponse(self.get_object().get_media('epub'))
270 class TagCategoryView(ListAPIView):
271 serializer_class = serializers.TagSerializer
273 def get_queryset(self):
274 category = self.kwargs['category']
275 tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
276 if self.request.query_params.get('book_only') == 'true':
277 tags = tags.filter(for_books=True)
278 if self.request.GET.get('picture_only') == 'true':
279 tags = filter(for_pictures=True)
281 after = self.request.query_params.get('after')
282 count = self.request.query_params.get('count')
284 tags = tags.filter(slug__gt=after)
291 class TagView(RetrieveAPIView):
292 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
293 serializer_class = serializers.TagDetailSerializer
294 queryset = Tag.objects.all()
296 def get_object(self):
297 return get_object_or_404(
299 category=self.kwargs['category'],
300 slug=self.kwargs['slug']
303 def post(self, request, **kwargs):
304 data = json.loads(request.POST.get('data'))
305 desc = data['description_pl']
306 obj = self.get_object()
307 obj.description_pl = desc
308 obj.save(update_fields=['description_pl'], quick=True)
312 @vary_on_auth # Because of 'liked'.
313 class FragmentList(ListAPIView):
314 serializer_class = serializers.FragmentSerializer
316 def get_queryset(self):
318 tags, ancestors = read_tags(
321 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
325 return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
328 @vary_on_auth # Because of 'liked'.
329 class FragmentView(RetrieveAPIView):
330 serializer_class = serializers.FragmentDetailSerializer
332 def get_object(self):
333 return get_object_or_404(
335 book__slug=self.kwargs['book'],
336 anchor=self.kwargs['anchor']