Fundraising in PDF.
[wolnelektury.git] / src / catalogue / api / views.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import json
5 import os.path
6 from urllib.request import urlopen
7 from django.conf import settings
8 from django.core.files.base import ContentFile
9 from django.http import Http404, HttpResponse
10 from django.utils.decorators import method_decorator
11 from django.views.decorators.cache import never_cache
12 from rest_framework.generics import (ListAPIView, RetrieveAPIView,
13                                      RetrieveUpdateAPIView, get_object_or_404)
14 from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
15 from rest_framework.response import Response
16 from rest_framework import status
17 from api.handlers import read_tags
18 from api.utils import vary_on_auth
19 from catalogue.forms import BookImportForm
20 from catalogue.models import Book, Collection, Tag, Fragment, BookMedia
21 from catalogue.models.tag import prefetch_relations
22 from club.models import Membership
23 from club.permissions import IsClubMember
24 from sortify import sortify
25 from wolnelektury.utils import re_escape
26 from .helpers import books_after, order_books
27 from . import serializers
28
29
30 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
31
32
33 class CreateOnPutMixin:
34     '''
35     Creates a new model instance when PUTting a nonexistent resource.
36     '''
37     def get_object(self):
38         try:
39             return super().get_object()
40         except Http404:
41             if self.request.method == 'PUT':
42                 lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
43                 return self.get_queryset().model(**{
44                     self.lookup_field: self.kwargs[lookup_url_kwarg]
45                 })
46             else:
47                 raise
48
49
50 class CollectionList(ListAPIView):
51     queryset = Collection.objects.filter(listed=True)
52     serializer_class = serializers.CollectionListSerializer
53
54
55 @vary_on_auth  # Because of 'liked'.
56 class CollectionDetail(CreateOnPutMixin, RetrieveUpdateAPIView):
57     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
58     queryset = Collection.objects.all()
59     lookup_field = 'slug'
60     serializer_class = serializers.CollectionSerializer
61
62
63 @vary_on_auth  # Because of 'liked'.
64 class BookList(ListAPIView):
65     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
66     queryset = Book.objects.none()  # Required for DjangoModelPermissions
67     serializer_class = serializers.BookListSerializer
68
69     def get(self, request, filename=None, **kwargs):
70         if filename and not kwargs.get('tags') and 'count' not in request.query_params:
71             try:
72                 with open(os.path.join(settings.MEDIA_ROOT, 'api', '%s.%s' % (filename, request.accepted_renderer.format)), 'rb') as f:
73                     content = f.read()
74                 return HttpResponse(content, content_type=request.accepted_media_type)
75             except:
76                 pass
77         return super().get(request, filename=filename, **kwargs)
78
79     def get_queryset(self):
80         try:
81             tags, ancestors = read_tags(
82                 self.kwargs.get('tags', ''), self.request,
83                 allowed=('author', 'epoch', 'kind', 'genre')
84             )
85         except ValueError:
86             raise Http404
87
88         new_api = self.request.query_params.get('new_api')
89         after = self.request.query_params.get('after', self.kwargs.get('after'))
90         count = self.request.query_params.get('count', self.kwargs.get('count'))
91         if count:
92             try:
93                 count = int(count)
94             except TypeError:
95                 raise Http404  # Fixme
96
97         if tags:
98             if self.kwargs.get('top_level'):
99                 books = Book.tagged_top_level(tags)
100                 if not books:
101                     raise Http404
102                 return books
103             else:
104                 books = Book.tagged.with_all(tags)
105         else:
106             books = Book.objects.all()
107         books = books.filter(findable=True)
108         books = order_books(books, new_api)
109
110         if not Membership.is_active_for(self.request.user):
111             books = books.exclude(preview=True)
112
113         if self.kwargs.get('top_level'):
114             books = books.filter(parent=None)
115         if self.kwargs.get('audiobooks'):
116             books = books.filter(media__type='mp3').distinct()
117         if self.kwargs.get('daisy'):
118             books = books.filter(media__type='daisy').distinct()
119         if self.kwargs.get('recommended'):
120             books = books.filter(recommended=True)
121         if self.kwargs.get('newest'):
122             books = books.order_by('-created_at')
123
124         if after:
125             books = books_after(books, after, new_api)
126
127         prefetch_relations(books, 'author')
128         prefetch_relations(books, 'genre')
129         prefetch_relations(books, 'kind')
130         prefetch_relations(books, 'epoch')
131
132         if count:
133             books = books[:count]
134
135         return books
136
137     def post(self, request, **kwargs):
138         if kwargs.get('audiobooks'):
139             return self.post_audiobook(request, **kwargs)
140         else:
141             return self.post_book(request, **kwargs)
142
143     def post_book(self, request, **kwargs):
144         data = json.loads(request.POST.get('data'))
145         form = BookImportForm(data)
146         if form.is_valid():
147             form.save()
148             return Response({}, status=status.HTTP_201_CREATED)
149         else:
150             raise Http404
151
152     def post_audiobook(self, request, **kwargs):
153         index = int(request.POST['part_index'])
154         parts_count = int(request.POST['parts_count'])
155         media_type = request.POST['type'].lower()
156         source_sha1 = request.POST.get('source_sha1')
157         name = request.POST.get('name', '')
158         part_name = request.POST.get('part_name', '')
159
160         project_description = request.POST.get('project_description', '')
161         project_icon = request.POST.get('project_icon', '')
162
163         _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
164         book = Book.objects.get(slug=slug)
165
166         try:
167             assert source_sha1
168             bm = book.media.get(type=media_type, source_sha1=source_sha1)
169         except (AssertionError, BookMedia.DoesNotExist):
170             bm = BookMedia(book=book, type=media_type)
171         bm.name = name
172         bm.part_name = part_name
173         bm.index = index
174         bm.project_description = project_description
175         bm.project_icon = project_icon
176         bm.file.save(None, request.data['file'], save=False)
177         bm.save(parts_count=parts_count)
178
179         return Response({}, status=status.HTTP_201_CREATED)
180
181
182 @vary_on_auth  # Because of 'liked'.
183 class BookDetail(RetrieveAPIView):
184     queryset = Book.objects.all()
185     lookup_field = 'slug'
186     serializer_class = serializers.BookDetailSerializer
187
188
189 @vary_on_auth  # Because of embargo links.
190 class EbookList(BookList):
191     serializer_class = serializers.EbookSerializer
192
193
194 @method_decorator(never_cache, name='dispatch')
195 class Preview(ListAPIView):
196     #queryset = Book.objects.filter(preview=True)
197     serializer_class = serializers.BookPreviewSerializer
198
199     def get_queryset(self):
200         qs = Book.objects.filter(preview=True)
201         # FIXME: temporary workaround for a problem with iOS app; see #3954.
202         if 'Darwin' in self.request.META.get('HTTP_USER_AGENT', '') and 'debug' not in self.request.GET:
203             qs = qs.none()
204         return qs
205
206
207 @vary_on_auth  # Because of 'liked'.
208 class FilterBookList(ListAPIView):
209     serializer_class = serializers.FilterBookListSerializer
210
211     def parse_bool(self, s):
212         if s in ('true', 'false'):
213             return s == 'true'
214         else:
215             return None
216
217     def get_queryset(self):
218         key_sep = '$'
219         search_string = self.request.query_params.get('search')
220         is_lektura = self.parse_bool(self.request.query_params.get('lektura'))
221         is_audiobook = self.parse_bool(self.request.query_params.get('audiobook'))
222         preview = self.parse_bool(self.request.query_params.get('preview'))
223         if not Membership.is_active_for(self.request.user):
224             preview = False
225
226         new_api = self.request.query_params.get('new_api')
227         after = self.request.query_params.get('after')
228         count = int(self.request.query_params.get('count', 50))
229         books = order_books(Book.objects.distinct(), new_api)
230         books = books.filter(findable=True)
231         if is_lektura is not None:
232             books = books.filter(has_audience=is_lektura)
233         if is_audiobook is not None:
234             if is_audiobook:
235                 books = books.filter(media__type='mp3')
236             else:
237                 books = books.exclude(media__type='mp3')
238         if preview is not None:
239             books = books.filter(preview=preview)
240         for category in book_tag_categories:
241             category_plural = category + 's'
242             if category_plural in self.request.query_params:
243                 slugs = self.request.query_params[category_plural].split(',')
244                 tags = Tag.objects.filter(category=category, slug__in=slugs)
245                 books = Book.tagged.with_any(tags, books)
246         if (search_string is not None) and len(search_string) < 3:
247             search_string = None
248         if search_string:
249             search_string = re_escape(search_string)
250             books_author = books.filter(cached_author__iregex=r'\m' + search_string)
251             books_title = books.filter(title__iregex=r'\m' + search_string)
252             books_title = books_title.exclude(id__in=list(books_author.values_list('id', flat=True)))
253             if after and (key_sep in after):
254                 which, key = after.split(key_sep, 1)
255                 if which == 'title':
256                     book_lists = [(books_after(books_title, key, new_api), 'title')]
257                 else:  # which == 'author'
258                     book_lists = [(books_after(books_author, key, new_api), 'author'), (books_title, 'title')]
259             else:
260                 book_lists = [(books_author, 'author'), (books_title, 'title')]
261         else:
262             if after and key_sep in after:
263                 which, key = after.split(key_sep, 1)
264                 books = books_after(books, key, new_api)
265             book_lists = [(books, 'book')]
266
267         filtered_books = []
268         for book_list, label in book_lists:
269             for category in book_tag_categories:
270                 book_list = prefetch_relations(book_list, category)
271             remaining_count = count - len(filtered_books)
272             for book in book_list[:remaining_count]:
273                 book.key = '%s%s%s' % (
274                     label, key_sep, book.slug if not new_api else book.full_sort_key())
275                 filtered_books.append(book)
276             if len(filtered_books) == count:
277                 break
278
279         return filtered_books
280
281
282 class EpubView(RetrieveAPIView):
283     queryset = Book.objects.all()
284     lookup_field = 'slug'
285     permission_classes = [IsClubMember]
286
287     @method_decorator(never_cache)
288     def get(self, *args, **kwargs):
289         return HttpResponse(self.get_object().get_media('epub'))
290
291
292 class TagCategoryView(ListAPIView):
293     serializer_class = serializers.TagSerializer
294
295     def get_queryset(self):
296         category = self.kwargs['category']
297         tags = Tag.objects.filter(category=category).exclude(items=None).order_by('slug')
298         if self.request.query_params.get('book_only') == 'true':
299             tags = tags.filter(for_books=True)
300         if self.request.GET.get('picture_only') == 'true':
301             tags = filter(for_pictures=True)
302
303         after = self.request.query_params.get('after')
304         count = self.request.query_params.get('count')
305         if after:
306             tags = tags.filter(slug__gt=after)
307         if count:
308             tags = tags[:count]
309
310         return tags
311
312
313 class TagView(RetrieveAPIView):
314     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
315     serializer_class = serializers.TagDetailSerializer
316     queryset = Tag.objects.all()
317     
318     def get_object(self):
319         try:
320             return get_object_or_404(
321                 Tag,
322                 category=self.kwargs['category'],
323                 slug=self.kwargs['slug']
324             )
325         except Http404:
326             if self.request.method == 'POST':
327                 return Tag(
328                     category=self.kwargs['category'],
329                     slug=self.kwargs['slug']
330                 )
331             else:
332                 raise
333
334     def post(self, request, **kwargs):
335         data = json.loads(request.POST.get('data'))
336         fields = {
337             "name_pl": "name_pl",
338             "description_pl": "description_pl",
339             "plural": "plural",
340             "is_epoch_specific": "genre_epoch_specific",
341             "collective_noun": "collective_noun",
342             "adjective_feminine_singular": "adjective_feminine_singular",
343             "adjective_nonmasculine_plural": "adjective_nonmasculine_plural",
344             "genitive": "genitive",
345             "collective_noun": "collective_noun",
346             "gazeta_link": "gazeta_link",
347             "culturepl_link": "culturepl_link",
348             "wiki_link_pl": "wiki_link_pl",
349             "photo_attribution": "photo_attribution",
350         }
351         obj = self.get_object()
352         updated = set()
353         for data_field, model_field in fields.items():
354             value = data.get(data_field)
355             if value:
356                 if obj.category == 'author' and model_field == 'name_pl':
357                     obj.sort_key = sortify(value.lower())
358                     updated.add('sort_key')
359                     value = ' '.join(reversed([t.strip() for t in value.split(',', 1)]))
360                 setattr(obj, model_field, value)
361                 updated.add(model_field)
362         if data.get('photo'):
363             response = urlopen(data['photo'])
364             ext = response.headers.get('Content-Type', '').rsplit('/', 1)[-1]
365             obj.photo.save(
366                 "{}.{}".format(self.kwargs['slug'], ext),
367                 ContentFile(response.read()),
368                 save=False,
369             )
370             updated.add('photo')
371
372         if obj.pk:
373             obj.save(update_fields=updated, quick=True)
374         else:
375             obj.save()
376         return Response({})
377
378
379 @vary_on_auth  # Because of 'liked'.
380 class FragmentList(ListAPIView):
381     serializer_class = serializers.FragmentSerializer
382
383     def get_queryset(self):
384         try:
385             tags, ancestors = read_tags(
386                 self.kwargs['tags'],
387                 self.request,
388                 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
389             )
390         except ValueError:
391             raise Http404
392         return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
393
394
395 @vary_on_auth  # Because of 'liked'.
396 class FragmentView(RetrieveAPIView):
397     serializer_class = serializers.FragmentDetailSerializer
398
399     def get_object(self):
400         return get_object_or_404(
401             Fragment,
402             book__slug=self.kwargs['book'],
403             anchor=self.kwargs['anchor']
404         )