1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
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
30 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
33 class CreateOnPutMixin:
35 Creates a new model instance when PUTting a nonexistent resource.
39 return super().get_object()
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]
50 class CollectionList(ListAPIView):
51 queryset = Collection.objects.filter(listed=True)
52 serializer_class = serializers.CollectionListSerializer
55 @vary_on_auth # Because of 'liked'.
56 class CollectionDetail(CreateOnPutMixin, RetrieveUpdateAPIView):
57 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
58 queryset = Collection.objects.all()
60 serializer_class = serializers.CollectionSerializer
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
69 def get(self, request, filename=None, **kwargs):
70 if filename and not kwargs.get('tags') and 'count' not in request.query_params:
72 with open(os.path.join(settings.MEDIA_ROOT, 'api', '%s.%s' % (filename, request.accepted_renderer.format)), 'rb') as f:
74 return HttpResponse(content, content_type=request.accepted_media_type)
77 return super().get(request, filename=filename, **kwargs)
79 def get_queryset(self):
81 tags, ancestors = read_tags(
82 self.kwargs.get('tags', ''), self.request,
83 allowed=('author', 'epoch', 'kind', 'genre')
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'))
98 if self.kwargs.get('top_level'):
99 books = Book.tagged_top_level(tags)
104 books = Book.tagged.with_all(tags)
106 books = Book.objects.all()
107 books = books.filter(findable=True)
108 books = order_books(books, new_api)
110 if not Membership.is_active_for(self.request.user):
111 books = books.exclude(preview=True)
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')
125 books = books_after(books, after, new_api)
127 prefetch_relations(books, 'author')
128 prefetch_relations(books, 'genre')
129 prefetch_relations(books, 'kind')
130 prefetch_relations(books, 'epoch')
133 books = books[:count]
137 def post(self, request, **kwargs):
138 if kwargs.get('audiobooks'):
139 return self.post_audiobook(request, **kwargs)
141 return self.post_book(request, **kwargs)
143 def post_book(self, request, **kwargs):
144 data = json.loads(request.POST.get('data'))
145 form = BookImportForm(data)
148 return Response({}, status=status.HTTP_201_CREATED)
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', '')
160 project_description = request.POST.get('project_description', '')
161 project_icon = request.POST.get('project_icon', '')
163 _rest, slug = request.POST['book'].rstrip('/').rsplit('/', 1)
164 book = Book.objects.get(slug=slug)
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)
172 bm.part_name = part_name
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)
179 return Response({}, status=status.HTTP_201_CREATED)
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
189 @vary_on_auth # Because of embargo links.
190 class EbookList(BookList):
191 serializer_class = serializers.EbookSerializer
194 @method_decorator(never_cache, name='dispatch')
195 class Preview(ListAPIView):
196 #queryset = Book.objects.filter(preview=True)
197 serializer_class = serializers.BookPreviewSerializer
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:
207 @vary_on_auth # Because of 'liked'.
208 class FilterBookList(ListAPIView):
209 serializer_class = serializers.FilterBookListSerializer
211 def parse_bool(self, s):
212 if s in ('true', 'false'):
217 def get_queryset(self):
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):
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:
235 books = books.filter(media__type='mp3')
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:
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)
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')]
260 book_lists = [(books_author, 'author'), (books_title, 'title')]
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')]
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:
279 return filtered_books
282 class EpubView(RetrieveAPIView):
283 queryset = Book.objects.all()
284 lookup_field = 'slug'
285 permission_classes = [IsClubMember]
287 @method_decorator(never_cache)
288 def get(self, *args, **kwargs):
289 return HttpResponse(self.get_object().get_media('epub'))
292 class TagCategoryView(ListAPIView):
293 serializer_class = serializers.TagSerializer
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)
303 after = self.request.query_params.get('after')
304 count = self.request.query_params.get('count')
306 tags = tags.filter(slug__gt=after)
313 class TagView(RetrieveAPIView):
314 permission_classes = [DjangoModelPermissionsOrAnonReadOnly]
315 serializer_class = serializers.TagDetailSerializer
316 queryset = Tag.objects.all()
318 def get_object(self):
320 return get_object_or_404(
322 category=self.kwargs['category'],
323 slug=self.kwargs['slug']
326 if self.request.method == 'POST':
328 category=self.kwargs['category'],
329 slug=self.kwargs['slug']
334 def post(self, request, **kwargs):
335 data = json.loads(request.POST.get('data'))
337 "name_pl": "name_pl",
338 "description_pl": "description_pl",
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",
351 obj = self.get_object()
353 for data_field, model_field in fields.items():
354 value = data.get(data_field)
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]
366 "{}.{}".format(self.kwargs['slug'], ext),
367 ContentFile(response.read()),
373 obj.save(update_fields=updated, quick=True)
379 @vary_on_auth # Because of 'liked'.
380 class FragmentList(ListAPIView):
381 serializer_class = serializers.FragmentSerializer
383 def get_queryset(self):
385 tags, ancestors = read_tags(
388 allowed={'author', 'epoch', 'kind', 'genre', 'book', 'theme'}
392 return Fragment.tagged.with_all(tags).filter(book__findable=True).select_related('book')
395 @vary_on_auth # Because of 'liked'.
396 class FragmentView(RetrieveAPIView):
397 serializer_class = serializers.FragmentDetailSerializer
399 def get_object(self):
400 return get_object_or_404(
402 book__slug=self.kwargs['book'],
403 anchor=self.kwargs['anchor']