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.
5 from django.http import Http404
6 from oauthlib.common import urlencode
7 from oauthlib.oauth1 import RequestTokenEndpoint
8 from piston.models import KEY_SIZE, SECRET_SIZE
9 from rest_framework.permissions import IsAuthenticated
10 from rest_framework.response import Response
11 from rest_framework.views import APIView
12 from rest_framework.generics import ListAPIView, RetrieveAPIView, get_object_or_404
13 from migdal.models import Entry
14 from catalogue.models import Book
15 from .models import BookUserData
16 from . import serializers
17 from .request_validator import PistonRequestValidator
18 from .utils import oauthlib_request, oauthlib_response
21 class OAuth1RequestTokenEndpoint(RequestTokenEndpoint):
22 def _create_request(self, *args, **kwargs):
23 r = super(OAuth1RequestTokenEndpoint, self)._create_request(*args, **kwargs)
24 r.redirect_uri = 'oob'
27 def create_request_token(self, request, credentials):
29 'oauth_token': self.token_generator()[:KEY_SIZE],
30 'oauth_token_secret': self.token_generator()[:SECRET_SIZE],
32 token.update(credentials)
33 self.request_validator.save_request_token(token, request)
34 return urlencode(token.items())
37 class OAuth1RequestTokenView(APIView):
39 self.endpoint = OAuth1RequestTokenEndpoint(PistonRequestValidator())
41 def dispatch(self, request):
42 return oauthlib_response(
43 self.endpoint.create_request_token_response(
44 **oauthlib_request(request)
49 class UserView(RetrieveAPIView):
50 permission_classes = [IsAuthenticated]
51 serializer_class = serializers.UserSerializer
54 return self.request.user
57 class BookUserDataView(RetrieveAPIView):
58 permission_classes = [IsAuthenticated]
59 serializer_class = serializers.BookUserDataSerializer
60 lookup_field = 'book__slug'
61 lookup_url_kwarg = 'slug'
63 def get_queryset(self):
64 return BookUserData.objects.filter(user=self.request.user)
66 def get(self, *args, **kwargs):
68 return super(BookUserDataView, self).get(*args, **kwargs)
70 return Response({"state": "not_started"})
72 def post(self, request, slug, state):
73 if state not in ('reading', 'complete'):
76 book = get_object_or_404(Book, slug=slug)
77 instance = BookUserData.update(book, request.user, state)
78 serializer = self.get_serializer(instance)
79 return Response(serializer.data)
82 class BlogView(ListAPIView):
83 serializer_class = serializers.BlogSerializer
85 def get_queryset(self):
86 after = self.request.query_params.get('after')
87 count = int(self.request.query_params.get('count', 20))
88 entries = Entry.published_objects.filter(in_stream=True).order_by('-first_published_at')
90 entries = entries.filter(first_published_at__lt=after)
92 entries = entries[:count]