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