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