fix
[wolnelektury.git] / src / catalogue / api / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 import os.path
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
25
26
27 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
28
29
30 class CreateOnPutMixin:
31     '''
32     Creates a new model instance when PUTting a nonexistent resource.
33     '''
34     def get_object(self):
35         try:
36             return super().get_object()
37         except Http404:
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]
42                 })
43             else:
44                 raise
45
46
47 class CollectionList(ListAPIView):
48     queryset = Collection.objects.filter(listed=True)
49     serializer_class = serializers.CollectionListSerializer
50
51
52 @vary_on_auth  # Because of 'liked'.
53 class CollectionDetail(CreateOnPutMixin, RetrieveUpdateAPIView):
54     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
55     queryset = Collection.objects.all()
56     lookup_field = 'slug'
57     serializer_class = serializers.CollectionSerializer
58
59
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
65
66     def get(self, request, filename=None, **kwargs):
67         if filename and not kwargs.get('tags') and 'count' not in request.query_params:
68             try:
69                 with open(os.path.join(settings.MEDIA_ROOT, 'api', '%s.%s' % (filename, request.accepted_renderer.format)), 'rb') as f:
70                     content = f.read()
71                 return HttpResponse(content, content_type=request.accepted_media_type)
72             except:
73                 pass
74         return super().get(request, filename=filename, **kwargs)
75
76     def get_queryset(self):
77         try:
78             tags, ancestors = read_tags(
79                 self.kwargs.get('tags', ''), self.request,
80                 allowed=('author', 'epoch', 'kind', 'genre')
81             )
82         except ValueError:
83             raise Http404
84
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'))
88         if count:
89             try:
90                 count = int(count)
91             except TypeError:
92                 raise Http404  # Fixme
93
94         if tags:
95             if self.kwargs.get('top_level'):
96                 books = Book.tagged_top_level(tags)
97                 if not books:
98                     raise Http404
99                 return books
100             else:
101                 books = Book.tagged.with_all(tags)
102         else:
103             books = Book.objects.all()
104         books = books.filter(findable=True)
105         books = order_books(books, new_api)
106
107         if not Membership.is_active_for(self.request.user):
108             books = books.exclude(preview=True)
109
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')
120
121         if after:
122             books = books_after(books, after, new_api)
123
124         prefetch_relations(books, 'author')
125         prefetch_relations(books, 'genre')
126         prefetch_relations(books, 'kind')
127         prefetch_relations(books, 'epoch')
128
129         if count:
130             books = books[:count]
131
132         return books
133
134     def post(self, request, **kwargs):
135         if kwargs.get('audiobooks'):
136             return self.post_audiobook(request, **kwargs)
137         else:
138             return self.post_book(request, **kwargs)
139
140     def post_book(self, request, **kwargs):
141         data = json.loads(request.POST.get('data'))
142         form = BookImportForm(data)
143         if form.is_valid():
144             form.save()
145             return Response({}, status=status.HTTP_201_CREATED)
146         else:
147             raise Http404
148
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', '')
156
157         project_description = request.POST.get('project_description', '')
158         project_icon = request.POST.get('project_icon', '')
159
160         _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
161         book = Book.objects.get(slug=slug)
162
163         try:
164             assert source_sha1
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)
168         bm.name = name
169         bm.part_name = part_name
170         bm.index = index
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)
175
176         return Response({}, status=status.HTTP_201_CREATED)
177
178
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
184
185
186 @vary_on_auth  # Because of embargo links.
187 class EbookList(BookList):
188     serializer_class = serializers.EbookSerializer
189
190
191 @method_decorator(never_cache, name='dispatch')
192 class Preview(ListAPIView):
193     #queryset = Book.objects.filter(preview=True)
194     serializer_class = serializers.BookPreviewSerializer
195
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:
200             qs = qs.none()
201         return qs
202
203
204 @vary_on_auth  # Because of 'liked'.
205 class FilterBookList(ListAPIView):
206     serializer_class = serializers.FilterBookListSerializer
207
208     def parse_bool(self, s):
209         if s in ('true', 'false'):
210             return s == 'true'
211         else:
212             return None
213
214     def get_queryset(self):
215         key_sep = '$'
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):
221             preview = False
222
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:
231             if is_audiobook:
232                 books = books.filter(media__type='mp3')
233             else:
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:
244             search_string = None
245         if search_string:
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)
252                 if which == 'title':
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')]
256             else:
257                 book_lists = [(books_author, 'author'), (books_title, 'title')]
258         else:
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')]
263
264         filtered_books = []
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:
274                 break
275
276         return filtered_books
277
278
279 class EpubView(RetrieveAPIView):
280     queryset = Book.objects.all()
281     lookup_field = 'slug'
282     permission_classes = [IsClubMember]
283
284     @method_decorator(never_cache)
285     def get(self, *args, **kwargs):
286         return HttpResponse(self.get_object().get_media('epub'))
287
288
289 class TagCategoryView(ListAPIView):
290     serializer_class = serializers.TagSerializer
291
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)
299
300         after = self.request.query_params.get('after')
301         count = self.request.query_params.get('count')
302         if after:
303             tags = tags.filter(slug__gt=after)
304         if count:
305             tags = tags[:count]
306
307         return tags
308
309
310 class TagView(RetrieveAPIView):
311     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
312     serializer_class = serializers.TagDetailSerializer
313     queryset = Tag.objects.all()
314     
315     def get_object(self):
316         try:
317             return get_object_or_404(
318                 Tag,
319                 category=self.kwargs['category'],
320                 slug=self.kwargs['slug']
321             )
322         except Http404:
323             if self.request.method == 'PUT':
324                 return Tag(
325                     category=self.kwargs['category'],
326                     slug=self.kwargs['slug']
327                 )
328             else:
329                 raise
330
331     def post(self, request, **kwargs):
332         data = json.loads(request.POST.get('data'))
333         desc = data['description_pl']
334         obj = self.get_object()
335         obj.description_pl = desc
336         obj.save(update_fields=['description_pl'], quick=True)
337         return Response({})
338
339
340 @vary_on_auth  # Because of 'liked'.
341 class FragmentList(ListAPIView):
342     serializer_class = serializers.FragmentSerializer
343
344     def get_queryset(self):
345         try:
346             tags, ancestors = read_tags(
347                 self.kwargs['tags'],
348                 self.request,
349                 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
350             )
351         except ValueError:
352             raise Http404
353         return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
354
355
356 @vary_on_auth  # Because of 'liked'.
357 class FragmentView(RetrieveAPIView):
358     serializer_class = serializers.FragmentDetailSerializer
359
360     def get_object(self):
361         return get_object_or_404(
362             Fragment,
363             book__slug=self.kwargs['book'],
364             anchor=self.kwargs['anchor']
365         )