fixes
[wolnelektury.git] / src / social / 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 from django.http import Http404
5 from rest_framework.generics import ListAPIView, get_object_or_404
6 from rest_framework.permissions import IsAuthenticated
7 from rest_framework.response import Response
8 from rest_framework.views import APIView
9 from api.models import BookUserData
10 from api.utils import vary_on_auth
11 from catalogue.api.helpers import order_books, books_after
12 from catalogue.api.serializers import BookSerializer
13 from catalogue.models import Book
14 from social.utils import likes
15
16
17 @vary_on_auth
18 class LikeView(APIView):
19     permission_classes = [IsAuthenticated]
20
21     def get(self, request, slug):
22         book = get_object_or_404(Book, slug=slug)
23         return Response({"likes": likes(request.user, book)})
24
25     def post(self, request, slug):
26         book = get_object_or_404(Book, slug=slug)
27         action = request.query_params.get('action', 'like')
28         if action == 'like':
29             book.like(request.user)
30         elif action == 'unlike':
31             book.unlike(request.user)
32         return Response({})
33
34
35 @vary_on_auth
36 class ShelfView(ListAPIView):
37     permission_classes = [IsAuthenticated]
38     serializer_class = BookSerializer
39
40     def get_queryset(self):
41         state = self.kwargs['state']
42         if state not in ('reading', 'complete', 'likes'):
43             raise Http404
44         new_api = self.request.query_params.get('new_api')
45         after = self.request.query_params.get('after')
46         count = int(self.request.query_params.get('count', 50))
47         if state == 'likes':
48             books = Book.tagged.with_any(self.request.user.tag_set.all())
49         else:
50             ids = BookUserData.objects.filter(user=self.request.user, complete=state == 'complete')\
51                 .values_list('book_id', flat=True)
52             books = Book.objects.filter(id__in=list(ids)).distinct()
53             books = order_books(books, new_api)
54         if after:
55             books = books_after(books, after, new_api)
56         if count:
57             books = books[:count]
58
59         return books
60