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,
11 RetrieveUpdateAPIView, get_object_or_404)
12 from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
13 from rest_framework.response import Response
14 from rest_framework import status
15 from api.handlers import read_tags
16 from api.utils import vary_on_auth
17 from catalogue.forms import BookImportForm
18 from catalogue.models import Book, Collection, Tag, Fragment, BookMedia
19 from catalogue.models.tag import prefetch_relations
20 from club.models import Membership
21 from club.permissions import IsClubMember
22 from wolnelektury.utils import re_escape
23 from .helpers import books_after, order_books
24 from . import serializers
27 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
30 class CreateOnPutMixin:
32 Creates a new model instance when PUTting a nonexistent resource.
36 return super().get_object()
38 if self.request.method == 'PUT':
39 lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
40 return self.get_queryset().model(**{
41 self.lookup_field: self.kwargs[lookup_url_kwarg]
47 class CollectionList(ListAPIView):
48 queryset = Collection.objects.filter(listed=True)
49 serializer_class = serializers.CollectionListSerializer
52 @vary_on_auth # Because of 'liked'.
53 class CollectionDetail(CreateOnPutMixin, RetrieveUpdateAPIView):
54 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
55 queryset = Collection.objects.all()
57 serializer_class = serializers.CollectionSerializer
60 @vary_on_auth # Because of 'liked'.
61 class BookList(ListAPIView):
62 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
63 queryset = Book.objects.none() # Required for DjangoModelPermissions
64 serializer_class = serializers.BookListSerializer
66 def get(self, request, filename=None, **kwargs):
67 if filename and not kwargs.get('tags') and 'count' not in request.query_params:
69 with open(os.path.join(settings.MEDIA_ROOT, 'api', '%s.%s' % (filename, request.accepted_renderer.format)), 'rb') as f:
71 return HttpResponse(content, content_type=request.accepted_media_type)
74 return super().get(request, filename=filename, **kwargs)
76 def get_queryset(self):
78 tags, ancestors = read_tags(
79 self.kwargs.get('tags', ''), self.request,
80 allowed=('author', 'epoch', 'kind', 'genre')
85 new_api = self.request.query_params.get('new_api')
86 after = self.request.query_params.get('after', self.kwargs.get('after'))
87 count = self.request.query_params.get('count', self.kwargs.get('count'))
95 if self.kwargs.get('top_level'):
96 books = Book.tagged_top_level(tags)
101 books = Book.tagged.with_all(tags)
103 books = Book.objects.all()
104 books = books.filter(findable=True)
105 books = order_books(books, new_api)
107 if not Membership.is_active_for(self.request.user):
108 books = books.exclude(preview=True)
110 if self.kwargs.get('top_level'):
111 books = books.filter(parent=None)
112 if self.kwargs.get('audiobooks'):
113 books = books.filter(media__type='mp3').distinct()
114 if self.kwargs.get('daisy'):
115 books = books.filter(media__type='daisy').distinct()
116 if self.kwargs.get('recommended'):
117 books = books.filter(recommended=True)
118 if self.kwargs.get('newest'):
119 books = books.order_by('-created_at')
122 books = books_after(books, after, new_api)
124 prefetch_relations(books, 'author')
125 prefetch_relations(books, 'genre')
126 prefetch_relations(books, 'kind')
127 prefetch_relations(books, 'epoch')
130 books = books[:count]
134 def post(self, request, **kwargs):
135 if kwargs.get('audiobooks'):
136 return self.post_audiobook(request, **kwargs)
138 return self.post_book(request, **kwargs)
140 def post_book(self, request, **kwargs):
141 data = json.loads(request.POST.get('data'))
142 form = BookImportForm(data)
145 return Response({}, status=status.HTTP_201_CREATED)
149 def post_audiobook(self, request, **kwargs):
150 index = int(request.POST['part_index'])
151 parts_count = int(request.POST['parts_count'])
152 media_type = request.POST['type'].lower()
153 source_sha1 = request.POST.get('source_sha1')
154 name = request.POST.get('name', '')
155 part_name = request.POST.get('part_name', '')
157 project_description = request.POST.get('project_description', '')
158 project_icon = request.POST.get('project_icon', '')
160 _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
161 book = Book.objects.get(slug=slug)
165 bm = book.media.get(type=media_type, source_sha1=source_sha1)
166 except (AssertionError, BookMedia.DoesNotExist):
167 bm = BookMedia(book=book, type=media_type)
169 bm.part_name = part_name
171 bm.project_description = project_description
172 bm.project_icon = project_icon
173 bm.file.save(None, request.data['file'], save=False)
174 bm.save(parts_count=parts_count)
176 return Response({}, status=status.HTTP_201_CREATED)
179 @vary_on_auth # Because of 'liked'.
180 class BookDetail(RetrieveAPIView):
181 queryset = Book.objects.all()
182 lookup_field = 'slug'
183 serializer_class = serializers.BookDetailSerializer
186 @vary_on_auth # Because of embargo links.
187 class EbookList(BookList):
188 serializer_class = serializers.EbookSerializer
191 @method_decorator(never_cache, name='dispatch')
192 class Preview(ListAPIView):
193 #queryset = Book.objects.filter(preview=True)
194 serializer_class = serializers.BookPreviewSerializer
196 def get_queryset(self):
197 qs = Book.objects.filter(preview=True)
198 # FIXME: temporary workaround for a problem with iOS app; see #3954.
199 if 'Darwin' in self.request.META.get('HTTP_USER_AGENT', '') and 'debug' not in self.request.GET:
204 @vary_on_auth # Because of 'liked'.
205 class FilterBookList(ListAPIView):
206 serializer_class = serializers.FilterBookListSerializer
208 def parse_bool(self, s):
209 if s in ('true', 'false'):
214 def get_queryset(self):
216 search_string = self.request.query_params.get('search')
217 is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
218 is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
219 preview = self.parse_bool(self.request.query_params.get('preview'))
220 if not Membership.is_active_for(self.request.user):
223 new_api = self.request.query_params.get('new_api')
224 after = self.request.query_params.get('after')
225 count = int(self.request.query_params.get('count', 50))
226 books = order_books(Book.objects.distinct(), new_api)
227 books = books.filter(findable=True)
228 if is_lektura is not None:
229 books = books.filter(has_audience=is_lektura)
230 if is_audiobook is not None:
232 books = books.filter(media__type='mp3')
234 books = books.exclude(media__type='mp3')
235 if preview is not None:
236 books = books.filter(preview=preview)
237 for category in book_tag_categories:
238 category_plural = category + 's'
239 if category_plural in self.request.query_params:
240 slugs = self.request.query_params[category_plural].split(',')
241 tags = Tag.objects.filter(category=category, slug__in=slugs)
242 books = Book.tagged.with_any(tags, books)
243 if (search_string is not None) and len(search_string) < 3:
246 search_string = re_escape(search_string)
247 books_author = books.filter(cached_author__iregex=r'\m' + search_string)
248 books_title = books.filter(title__iregex=r'\m' + search_string)
249 books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
250 if after and (key_sep in after):
251 which, key = after.split(key_sep, 1)
253 book_lists = [(books_after(books_title, key, new_api), 'title')]
254 else: # which == 'author'
255 book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
257 book_lists = [(books_author, 'author'), (books_title, 'title')]
259 if after and key_sep in after:
260 which, key = after.split(key_sep, 1)
261 books = books_after(books, key, new_api)
262 book_lists = [(books, 'book')]
265 for book_list, label in book_lists:
266 for category in book_tag_categories:
267 book_list = prefetch_relations(book_list, category)
268 remaining_count = count - len(filtered_books)
269 for book in book_list[:remaining_count]:
270 book.key = '%s%s%s' % (
271 label, key_sep, book.slug if not new_api else book.full_sort_key())
272 filtered_books.append(book)
273 if len(filtered_books) == count:
276 return filtered_books
279 class EpubView(RetrieveAPIView):
280 queryset = Book.objects.all()
281 lookup_field = 'slug'
282 permission_classes = [IsClubMember]
284 @method_decorator(never_cache)
285 def get(self, *args, **kwargs):
286 return HttpResponse(self.get_object().get_media('epub'))
289 class TagCategoryView(ListAPIView):
290 serializer_class = serializers.TagSerializer
292 def get_queryset(self):
293 category = self.kwargs['category']
294 tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
295 if self.request.query_params.get('book_only') == 'true':
296 tags = tags.filter(for_books=True)
297 if self.request.GET.get('picture_only') == 'true':
298 tags = filter(for_pictures=True)
300 after = self.request.query_params.get('after')
301 count = self.request.query_params.get('count')
303 tags = tags.filter(slug__gt=after)
310 class TagView(RetrieveAPIView):
311 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
312 serializer_class = serializers.TagDetailSerializer
313 queryset = Tag.objects.all()
315 def get_object(self):
317 return get_object_or_404(
319 category=self.kwargs['category'],
320 slug=self.kwargs['slug']
323 if self.request.method == 'POST':
325 category=self.kwargs['category'],
326 slug=self.kwargs['slug']
331 def post(self, request, **kwargs):
332 data = json.loads(request.POST.get('data'))
334 "description_pl": "description_pl",
336 "is_epoch_specific": "genre_epoch_specific",
337 "collective_noun": "collective_noun",
338 "adjective_feminine_singular": "adjective_feminine_singular",
339 "adjective_nonmasculine_plural": "adjective_nonmasculine_plural",
341 obj = self.get_object()
342 for data_field, model_field in fields.items():
343 setattr(obj, model_field, data.get(data_field, getattr(obj, model_field)))
345 obj.save(update_fields=fields.values(), quick=True)
351 @vary_on_auth # Because of 'liked'.
352 class FragmentList(ListAPIView):
353 serializer_class = serializers.FragmentSerializer
355 def get_queryset(self):
357 tags, ancestors = read_tags(
360 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
364 return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
367 @vary_on_auth # Because of 'liked'.
368 class FragmentView(RetrieveAPIView):
369 serializer_class = serializers.FragmentDetailSerializer
371 def get_object(self):
372 return get_object_or_404(
374 book__slug=self.kwargs['book'],
375 anchor=self.kwargs['anchor']