Bugfix
[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 from django.http import Http404, HttpResponse
6 from django.utils.decorators import method_decorator
7 from django.views.decorators.cache import never_cache
8 from rest_framework.generics import ListAPIView, RetrieveAPIView, get_object_or_404
9 from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
10 from rest_framework.response import Response
11 from rest_framework import status
12 from api.handlers import read_tags
13 from api.utils import vary_on_auth
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.models import Membership
18 from club.permissions import IsClubMember
19 from wolnelektury.utils import re_escape
20 from .helpers import books_after, order_books
21 from . import serializers
22
23
24 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
25
26
27 class CollectionList(ListAPIView):
28     queryset = Collection.objects.all()
29     serializer_class = serializers.CollectionListSerializer
30
31
32 @vary_on_auth  # Because of 'liked'.
33 class CollectionDetail(RetrieveAPIView):
34     queryset = Collection.objects.all()
35     lookup_field = 'slug'
36     serializer_class = serializers.CollectionSerializer
37
38
39 @vary_on_auth  # Because of 'liked'.
40 class BookList(ListAPIView):
41     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
42     queryset = Book.objects.none()  # Required for DjangoModelPermissions
43     serializer_class = serializers.BookListSerializer
44
45     def get_queryset(self):
46         try:
47             tags, ancestors = read_tags(
48                 self.kwargs.get('tags', ''), self.request,
49                 allowed=('author', 'epoch', 'kind', 'genre')
50             )
51         except ValueError:
52             raise Http404
53
54         new_api = self.request.query_params.get('new_api')
55         after = self.request.query_params.get('after', self.kwargs.get('after'))
56         count = self.request.query_params.get('count', self.kwargs.get('count'))
57         if count:
58             try:
59                 count = int(count)
60             except TypeError:
61                 raise Http404  # Fixme
62
63         if tags:
64             if self.kwargs.get('top_level'):
65                 books = Book.tagged_top_level(tags)
66                 if not books:
67                     raise Http404
68                 return books
69             else:
70                 books = Book.tagged.with_all(tags)
71         else:
72             books = Book.objects.all()
73         books = books.filter(findable=True)
74         books = order_books(books, new_api)
75
76         if not Membership.is_active_for(self.request.user):
77             books = books.exclude(preview=True)
78
79         if self.kwargs.get('top_level'):
80             books = books.filter(parent=None)
81         if self.kwargs.get('audiobooks'):
82             books = books.filter(media__type='mp3').distinct()
83         if self.kwargs.get('daisy'):
84             books = books.filter(media__type='daisy').distinct()
85         if self.kwargs.get('recommended'):
86             books = books.filter(recommended=True)
87         if self.kwargs.get('newest'):
88             books = books.order_by('-created_at')
89
90         if after:
91             books = books_after(books, after, new_api)
92
93         prefetch_relations(books, 'author')
94         prefetch_relations(books, 'genre')
95         prefetch_relations(books, 'kind')
96         prefetch_relations(books, 'epoch')
97
98         if count:
99             books = books[:count]
100
101         return books
102
103     def post(self, request, **kwargs):
104         if kwargs.get('audiobooks'):
105             return self.post_audiobook(request, **kwargs)
106         else:
107             return self.post_book(request, **kwargs)
108
109     def post_book(self, request, **kwargs):
110         data = json.loads(request.POST.get('data'))
111         form = BookImportForm(data)
112         if form.is_valid():
113             form.save()
114             return Response({}, status=status.HTTP_201_CREATED)
115         else:
116             raise Http404
117
118     def post_audiobook(self, request, **kwargs):
119         index = int(request.POST['part_index'])
120         parts_count = int(request.POST['parts_count'])
121         media_type = request.POST['type'].lower()
122         source_sha1 = request.POST.get('source_sha1')
123         name = request.POST.get('name', '')
124         part_name = request.POST.get('part_name', '')
125
126         _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
127         book = Book.objects.get(slug=slug)
128
129         try:
130             assert source_sha1
131             bm = book.media.get(type=media_type, source_sha1=source_sha1)
132         except (AssertionError, BookMedia.DoesNotExist):
133             bm = BookMedia(book=book, type=media_type)
134         bm.name = name
135         bm.part_name = part_name
136         bm.index = index
137         bm.file.save(None, request.data['file'], save=False)
138         bm.save(parts_count=parts_count)
139
140         return Response({}, status=status.HTTP_201_CREATED)
141
142
143 @vary_on_auth  # Because of 'liked'.
144 class BookDetail(RetrieveAPIView):
145     queryset = Book.objects.all()
146     lookup_field = 'slug'
147     serializer_class = serializers.BookDetailSerializer
148
149
150 @vary_on_auth  # Because of embargo links.
151 class EbookList(BookList):
152     serializer_class = serializers.EbookSerializer
153
154
155 @method_decorator(never_cache, name='dispatch')
156 class Preview(ListAPIView):
157     #queryset = Book.objects.filter(preview=True)
158     serializer_class = serializers.BookPreviewSerializer
159
160     def get_queryset(self):
161         qs = Book.objects.filter(preview=True)
162         # FIXME: temporary workaround for a problem with iOS app; see #3954.
163         if 'Darwin' in self.request.META.get('HTTP_USER_AGENT', '') and 'debug' not in self.request.GET:
164             qs = qs.none()
165         return qs
166
167
168 @vary_on_auth  # Because of 'liked'.
169 class FilterBookList(ListAPIView):
170     serializer_class = serializers.FilterBookListSerializer
171
172     def parse_bool(self, s):
173         if s in ('true', 'false'):
174             return s == 'true'
175         else:
176             return None
177
178     def get_queryset(self):
179         key_sep = '$'
180         search_string = self.request.query_params.get('search')
181         is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
182         is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
183         preview = self.parse_bool(self.request.query_params.get('preview'))
184         if not Membership.is_active_for(self.request.user):
185             preview = False
186
187         new_api = self.request.query_params.get('new_api')
188         after = self.request.query_params.get('after')
189         count = int(self.request.query_params.get('count', 50))
190         books = order_books(Book.objects.distinct(), new_api)
191         books = books.filter(findable=True)
192         if is_lektura is not None:
193             books = books.filter(has_audience=is_lektura)
194         if is_audiobook is not None:
195             if is_audiobook:
196                 books = books.filter(media__type='mp3')
197             else:
198                 books = books.exclude(media__type='mp3')
199         if preview is not None:
200             books = books.filter(preview=preview)
201         for category in book_tag_categories:
202             category_plural = category + 's'
203             if category_plural in self.request.query_params:
204                 slugs = self.request.query_params[category_plural].split(',')
205                 tags = Tag.objects.filter(category=category, slug__in=slugs)
206                 books = Book.tagged.with_any(tags, books)
207         if (search_string is not None) and len(search_string) < 3:
208             search_string = None
209         if search_string:
210             search_string = re_escape(search_string)
211             books_author = books.filter(cached_author__iregex=r'\m' + search_string)
212             books_title = books.filter(title__iregex=r'\m' + search_string)
213             books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
214             if after and (key_sep in after):
215                 which, key = after.split(key_sep, 1)
216                 if which == 'title':
217                     book_lists = [(books_after(books_title, key, new_api), 'title')]
218                 else:  # which == 'author'
219                     book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
220             else:
221                 book_lists = [(books_author, 'author'), (books_title, 'title')]
222         else:
223             if after and key_sep in after:
224                 which, key = after.split(key_sep, 1)
225                 books = books_after(books, key, new_api)
226             book_lists = [(books, 'book')]
227
228         filtered_books = []
229         for book_list, label in book_lists:
230             for category in book_tag_categories:
231                 book_list = prefetch_relations(book_list, category)
232             remaining_count = count - len(filtered_books)
233             for book in book_list[:remaining_count]:
234                 book.key = '%s%s%s' % (
235                     label, key_sep, book.slug if not new_api else book.full_sort_key())
236                 filtered_books.append(book)
237             if len(filtered_books) == count:
238                 break
239
240         return filtered_books
241
242
243 class EpubView(RetrieveAPIView):
244     queryset = Book.objects.all()
245     lookup_field = 'slug'
246     permission_classes = [IsClubMember]
247
248     @method_decorator(never_cache)
249     def get(self, *args, **kwargs):
250         return HttpResponse(self.get_object().get_media('epub'))
251
252
253 class TagCategoryView(ListAPIView):
254     serializer_class = serializers.TagSerializer
255
256     def get_queryset(self):
257         category = self.kwargs['category']
258         tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
259         if self.request.query_params.get('book_only') == 'true':
260             tags = tags.filter(for_books=True)
261         if self.request.GET.get('picture_only') == 'true':
262             tags = filter(for_pictures=True)
263
264         after = self.request.query_params.get('after')
265         count = self.request.query_params.get('count')
266         if after:
267             tags = tags.filter(slug__gt=after)
268         if count:
269             tags = tags[:count]
270
271         return tags
272
273
274 class TagView(RetrieveAPIView):
275     serializer_class = serializers.TagDetailSerializer
276
277     def get_object(self):
278         return get_object_or_404(
279             Tag,
280             category=self.kwargs['category'],
281             slug=self.kwargs['slug']
282         )
283
284
285 @vary_on_auth  # Because of 'liked'.
286 class FragmentList(ListAPIView):
287     serializer_class = serializers.FragmentSerializer
288
289     def get_queryset(self):
290         try:
291             tags, ancestors = read_tags(
292                 self.kwargs['tags'],
293                 self.request,
294                 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
295             )
296         except ValueError:
297             raise Http404
298         return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
299
300
301 @vary_on_auth  # Because of 'liked'.
302 class FragmentView(RetrieveAPIView):
303     serializer_class = serializers.FragmentDetailSerializer
304
305     def get_object(self):
306         return get_object_or_404(
307             Fragment,
308             book__slug=self.kwargs['book'],
309             anchor=self.kwargs['anchor']
310         )