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