377beb6812a248f32715ede67a9b745beb9830a0
[wolnelektury.git] / src / 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.permissions import IsAuthenticated
7 from rest_framework.response import Response
8 from rest_framework.views import APIView
9 from rest_framework.generics import ListAPIView, RetrieveAPIView, get_object_or_404
10 from migdal.models import Entry
11 from catalogue.models import Book
12 from .models import BookUserData
13 from . import serializers
14
15
16 class UserView(RetrieveAPIView):
17     permission_classes = [IsAuthenticated]
18     serializer_class = serializers.UserSerializer
19
20     def get_object(self):
21         return self.request.user
22
23
24 class BookUserDataView(RetrieveAPIView):
25     permission_classes = [IsAuthenticated]
26     serializer_class = serializers.BookUserDataSerializer
27     lookup_field = 'book__slug'
28     lookup_url_kwarg = 'slug'
29
30     def get_queryset(self):
31         return BookUserData.objects.filter(user=self.request.user)
32
33     def get(self, *args, **kwargs):
34         try:
35             return super(BookUserDataView, self).get(*args, **kwargs)
36         except Http404:
37             return Response({"state": "not_started"})
38
39     def post(self, request, slug, state):
40         if state not in ('reading', 'complete'):
41             raise Http404
42
43         book = get_object_or_404(Book, slug=slug)
44         instance = BookUserData.update(book, request.user, state)
45         serializer = self.get_serializer(instance)
46         return Response(serializer.data)
47
48
49 class BlogView(ListAPIView):
50     serializer_class = serializers.BlogSerializer
51
52     def get_queryset(self):
53         after = self.request.query_params.get('after')
54         count = int(self.request.query_params.get('count', 20))
55         entries = Entry.published_objects.filter(in_stream=True).order_by('-first_published_at')
56         if after:
57             entries = entries.filter(first_published_at__lt=after)
58         if count:
59             entries = entries[:count]
60         return entries