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