All views migrated from Piston, except for OAuth.
[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 .helpers import books_after, order_books
14 from . import serializers
15 from catalogue.forms import BookImportForm
16 from catalogue.models import Book, Collection, Tag, Fragment
17 from catalogue.models.tag import prefetch_relations
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 class CollectionDetail(RetrieveAPIView):
30     queryset = Collection.objects.all()
31     lookup_field = 'slug'
32     serializer_class = serializers.CollectionSerializer
33
34
35 class BookList(ListAPIView):
36     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
37     queryset = Book.objects.none()  # Required for DjangoModelPermissions
38     serializer_class = serializers.BookListSerializer
39
40     def get_queryset(self):
41         try:
42             tags, ancestors = read_tags(
43                 self.kwargs.get('tags', ''), self.request,
44                 allowed=('author', 'epoch', 'kind', 'genre')
45             )
46         except ValueError:
47             raise Http404
48
49         new_api = self.request.query_params.get('new_api')
50         after = self.request.query_params.get('after', self.kwargs.get('after'))
51         count = self.request.query_params.get('count', self.kwargs.get('count'))
52
53         if tags:
54             if self.kwargs.get('top_level'):
55                 books = Book.tagged_top_level(tags)
56                 if not books:
57                     raise Http404
58                 return books
59             else:
60                 books = Book.tagged.with_all(tags)
61         else:
62             books = Book.objects.all()
63         books = order_books(books, new_api)
64
65         if self.kwargs.get('top_level'):
66             books = books.filter(parent=None)
67         if self.kwargs.get('audiobooks'):
68             books = books.filter(media__type='mp3').distinct()
69         if self.kwargs.get('daisy'):
70             books = books.filter(media__type='daisy').distinct()
71         if self.kwargs.get('recommended'):
72             books = books.filter(recommended=True)
73         if self.kwargs.get('newest'):
74             books = books.order_by('-created_at')
75
76         if after:
77             books = books_after(books, after, new_api)
78
79         prefetch_relations(books, 'author')
80         prefetch_relations(books, 'genre')
81         prefetch_relations(books, 'kind')
82         prefetch_relations(books, 'epoch')
83
84         if count:
85             books = books[:count]
86
87         return books
88
89     def post(self, request, **kwargs):
90         # Permission needed.
91         data = json.loads(request.POST.get('data'))
92         form = BookImportForm(data)
93         if form.is_valid():
94             form.save()
95             return Response({}, status=status.HTTP_201_CREATED)
96         else:
97             raise Http404
98
99
100 class BookDetail(RetrieveAPIView):
101     queryset = Book.objects.all()
102     lookup_field = 'slug'
103     serializer_class = serializers.BookDetailSerializer
104
105
106 class EbookList(BookList):
107     serializer_class = serializers.EbookSerializer
108
109
110 class Preview(ListAPIView):
111     queryset = Book.objects.filter(preview=True)
112     serializer_class = serializers.BookPreviewSerializer
113
114
115 class FilterBookList(ListAPIView):
116     serializer_class = serializers.FilterBookListSerializer
117
118     def parse_bool(self, s):
119         if s in ('true', 'false'):
120             return s == 'true'
121         else:
122             return None
123
124     def get_queryset(self):
125         key_sep = '$'
126         search_string = self.request.query_params.get('search')
127         is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
128         is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
129         preview = self.parse_bool(self.request.query_params.get('preview'))
130
131         new_api = self.request.query_params.get('new_api')
132         after = self.request.query_params.get('after')
133         count = int(self.request.query_params.get('count', 50))
134         books = order_books(Book.objects.distinct(), new_api)
135         if is_lektura is not None:
136             books = books.filter(has_audience=is_lektura)
137         if is_audiobook is not None:
138             if is_audiobook:
139                 books = books.filter(media__type='mp3')
140             else:
141                 books = books.exclude(media__type='mp3')
142         if preview is not None:
143             books = books.filter(preview=preview)
144         for category in book_tag_categories:
145             category_plural = category + 's'
146             if category_plural in self.request.query_params:
147                 slugs = self.request.query_params[category_plural].split(',')
148                 tags = Tag.objects.filter(category=category, slug__in=slugs)
149                 books = Book.tagged.with_any(tags, books)
150         if (search_string is not None) and len(search_string) < 3:
151             search_string = None
152         if search_string:
153             search_string = re_escape(search_string)
154             books_author = books.filter(cached_author__iregex=r'\m' + search_string)
155             books_title = books.filter(title__iregex=r'\m' + search_string)
156             books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
157             if after and (key_sep in after):
158                 which, key = after.split(key_sep, 1)
159                 if which == 'title':
160                     book_lists = [(books_after(books_title, key, new_api), 'title')]
161                 else:  # which == 'author'
162                     book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
163             else:
164                 book_lists = [(books_author, 'author'), (books_title, 'title')]
165         else:
166             if after and key_sep in after:
167                 which, key = after.split(key_sep, 1)
168                 books = books_after(books, key, new_api)
169             book_lists = [(books, 'book')]
170
171         filtered_books = []
172         for book_list, label in book_lists:
173             for category in book_tag_categories:
174                 book_list = prefetch_relations(book_list, category)
175             remaining_count = count - len(filtered_books)
176             for book in book_list[:remaining_count]:
177                 book.key = '%s%s%s' % (
178                     label, key_sep, book.slug if not new_api else book.full_sort_key())
179                 filtered_books.append(book)
180             if len(filtered_books) == count:
181                 break
182
183         return filtered_books
184
185
186 class EpubView(RetrieveAPIView):
187     queryset = Book.objects.all()
188     lookup_field = 'slug'
189     permission_classes = [IsSubscribed]
190
191     def get(self, *args, **kwargs):
192         return HttpResponse(self.get_object().get_media('epub'))
193
194
195 class TagCategoryView(ListAPIView):
196     serializer_class = serializers.TagSerializer
197
198     def get_queryset(self):
199         category = self.kwargs['category']
200         tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
201         if self.request.query_params.get('book_only') == 'true':
202             tags = tags.filter(for_books=True)
203         if self.request.GET.get('picture_only') == 'true':
204             tags = filter(for_pictures=True)
205
206         after = self.request.query_params.get('after')
207         count = self.request.query_params.get('count')
208         if after:
209             tags = tags.filter(slug__gt=after)
210         if count:
211             tags = tags[:count]
212
213         return tags
214
215
216 class TagView(RetrieveAPIView):
217     serializer_class = serializers.TagDetailSerializer
218
219     def get_object(self):
220         return get_object_or_404(
221             Tag,
222             category=self.kwargs['category'],
223             slug=self.kwargs['slug']
224         )
225
226
227 class FragmentList(ListAPIView):
228     serializer_class = serializers.FragmentSerializer
229
230     def get_queryset(self):
231         try:
232             tags, ancestors = read_tags(
233                 self.kwargs['tags'],
234                 self.request,
235                 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
236             )
237         except ValueError:
238             raise Http404
239         return Fragment.tagged.with_all(tags).select_related('book')
240
241
242 class FragmentView(RetrieveAPIView):
243     serializer_class = serializers.FragmentDetailSerializer
244
245     def get_object(self):
246         return get_object_or_404(
247             Fragment,
248             book__slug=self.kwargs['book'],
249             anchor=self.kwargs['anchor']
250         )