Pictures: leave raw models for archiving.
[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
299         after = self.request.query_params.get('after')
300         count = self.request.query_params.get('count')
301         if after:
302             tags = tags.filter(slug__gt=after)
303         if count:
304             tags = tags[:count]
305
306         return tags
307
308
309 class TagView(RetrieveAPIView):
310     permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
311     serializer_class = serializers.TagDetailSerializer
312     queryset = Tag.objects.all()
313     
314     def get_object(self):
315         try:
316             return get_object_or_404(
317                 Tag,
318                 category=self.kwargs['category'],
319                 slug=self.kwargs['slug']
320             )
321         except Http404:
322             if self.request.method == 'POST':
323                 return Tag(
324                     category=self.kwargs['category'],
325                     slug=self.kwargs['slug']
326                 )
327             else:
328                 raise
329
330     def post(self, request, **kwargs):
331         data = json.loads(request.POST.get('data'))
332         fields = {
333             "name_pl": "name_pl",
334             "description_pl": "description_pl",
335             "plural": "plural",
336             "is_epoch_specific": "genre_epoch_specific",
337             "collective_noun": "collective_noun",
338             "adjective_feminine_singular": "adjective_feminine_singular",
339             "adjective_nonmasculine_plural": "adjective_nonmasculine_plural",
340             "genitive": "genitive",
341             "collective_noun": "collective_noun",
342             "gazeta_link": "gazeta_link",
343             "culturepl_link": "culturepl_link",
344             "wiki_link_pl": "wiki_link_pl",
345             "photo_attribution": "photo_attribution",
346         }
347         obj = self.get_object()
348         updated = set()
349         for data_field, model_field in fields.items():
350             value = data.get(data_field)
351             if value:
352                 if obj.category == 'author' and model_field == 'name_pl':
353                     obj.sort_key = sortify(value.lower())
354                     updated.add('sort_key')
355                     value = ' '.join(reversed([t.strip() for t in value.split(',', 1)]))
356                 setattr(obj, model_field, value)
357                 updated.add(model_field)
358         if data.get('photo'):
359             response = urlopen(data['photo'])
360             ext = response.headers.get('Content-Type', '').rsplit('/', 1)[-1]
361             obj.photo.save(
362                 "{}.{}".format(self.kwargs['slug'], ext),
363                 ContentFile(response.read()),
364                 save=False,
365             )
366             updated.add('photo')
367
368         if obj.pk:
369             obj.save(update_fields=updated, quick=True)
370         else:
371             obj.save()
372         return Response({})
373
374
375 @vary_on_auth  # Because of 'liked'.
376 class FragmentList(ListAPIView):
377     serializer_class = serializers.FragmentSerializer
378
379     def get_queryset(self):
380         try:
381             tags, ancestors = read_tags(
382                 self.kwargs['tags'],
383                 self.request,
384                 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
385             )
386         except ValueError:
387             raise Http404
388         return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
389
390
391 @vary_on_auth  # Because of 'liked'.
392 class FragmentView(RetrieveAPIView):
393     serializer_class = serializers.FragmentDetailSerializer
394
395     def get_object(self):
396         return get_object_or_404(
397             Fragment,
398             book__slug=self.kwargs['book'],
399             anchor=self.kwargs['anchor']
400         )