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