Introduce DRF and start replacing the views.
[wolnelektury.git] / src / api / handlers.py
index cee41f4..f3cc4a7 100644 (file)
@@ -19,8 +19,7 @@ from api.models import BookUserData
 from catalogue.forms import BookImportForm
 from catalogue.models import Book, Tag, BookMedia, Fragment, Collection
 from catalogue.models.tag import prefetch_relations
 from catalogue.forms import BookImportForm
 from catalogue.models import Book, Tag, BookMedia, Fragment, Collection
 from catalogue.models.tag import prefetch_relations
-from catalogue.utils import is_subscribed
-from librarian.cover import WLCover
+from paypal.rest import user_is_subscribed
 from picture.models import Picture
 from picture.forms import PictureImportForm
 from social.utils import likes
 from picture.models import Picture
 from picture.forms import PictureImportForm
 from social.utils import likes
@@ -33,8 +32,6 @@ from . import emitters  # Register our emitters
 API_BASE = WL_BASE = MEDIA_BASE = lazy(
     lambda: u'https://' + Site.objects.get_current().domain, unicode)()
 
 API_BASE = WL_BASE = MEDIA_BASE = lazy(
     lambda: u'https://' + Site.objects.get_current().domain, unicode)()
 
-SORT_KEY_SEP = ','
-
 category_singular = {
     'authors': 'author',
     'kinds': 'kind',
 category_singular = {
     'authors': 'author',
     'kinds': 'kind',
@@ -63,6 +60,7 @@ def read_tags(tags, request, allowed):
 
     def process(category, slug):
         if category == 'book':
 
     def process(category, slug):
         if category == 'book':
+            # FIXME: Unused?
             try:
                 books.append(Book.objects.get(slug=slug))
             except Book.DoesNotExist:
             try:
                 books.append(Book.objects.get(slug=slug))
             except Book.DoesNotExist:
@@ -130,7 +128,7 @@ class BookDetails(object):
     @classmethod
     def href(cls, book):
         """ Returns an URI for a Book in the API. """
     @classmethod
     def href(cls, book):
         """ Returns an URI for a Book in the API. """
-        return API_BASE + reverse("api_book", args=[book.slug])
+        return API_BASE + reverse("catalogue_api_book", args=[book.slug])
 
     @classmethod
     def url(cls, book):
 
     @classmethod
     def url(cls, book):
@@ -164,22 +162,14 @@ class BookDetails(object):
     def simple_cover(cls, book):
         return MEDIA_BASE + book.simple_cover.url if book.simple_cover else ''
 
     def simple_cover(cls, book):
         return MEDIA_BASE + book.simple_cover.url if book.simple_cover else ''
 
-    @classmethod
-    def cover_color(cls, book):
-        return WLCover.epoch_colors.get(book.extra_info.get('epoch'), '#000000')
-
-    @classmethod
-    def full_sort_key(cls, book):
-        return '%s%s%s%s%s' % (book.sort_key_author, SORT_KEY_SEP, book.sort_key, SORT_KEY_SEP, book.id)
-
     @staticmethod
     def books_after(books, after, new_api):
         if not new_api:
             return books.filter(slug__gt=after)
         try:
     @staticmethod
     def books_after(books, after, new_api):
         if not new_api:
             return books.filter(slug__gt=after)
         try:
-            author, title, book_id = after.split(SORT_KEY_SEP)
+            author, title, book_id = after.split(Book.SORT_KEY_SEP)
         except ValueError:
         except ValueError:
-            return []
+            return Book.objects.none()
         return books.filter(Q(sort_key_author__gt=author)
                             | (Q(sort_key_author=author) & Q(sort_key__gt=title))
                             | (Q(sort_key_author=author) & Q(sort_key=title) & Q(id__gt=int(book_id))))
         return books.filter(Q(sort_key_author__gt=author)
                             | (Q(sort_key_author=author) & Q(sort_key__gt=title))
                             | (Q(sort_key_author=author) & Q(sort_key=title) & Q(id__gt=int(book_id))))
@@ -221,6 +211,7 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
     model = Book
     fields = book_list_fields
 
     model = Book
     fields = book_list_fields
 
+    # FIXME: Unused?
     @classmethod
     def genres(cls, book):
         """ Returns all media for a book. """
     @classmethod
     def genres(cls, book):
         """ Returns all media for a book. """
@@ -239,6 +230,7 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
              are returned.
         """
         if pk is not None:
              are returned.
         """
         if pk is not None:
+            # FIXME: Unused?
             try:
                 return Book.objects.get(pk=pk)
             except Book.DoesNotExist:
             try:
                 return Book.objects.get(pk=pk)
             except Book.DoesNotExist:
@@ -330,7 +322,7 @@ class BooksHandler(BookDetailHandler):
 
 class EpubHandler(BookDetailHandler):
     def read(self, request, slug):
 
 class EpubHandler(BookDetailHandler):
     def read(self, request, slug):
-        if not is_subscribed(request.user):
+        if not user_is_subscribed(request.user):
             return rc.FORBIDDEN
         try:
             book = Book.objects.get(slug=slug)
             return rc.FORBIDDEN
         try:
             book = Book.objects.get(slug=slug)
@@ -378,16 +370,13 @@ class AnonFilterBooksHandler(AnonymousBooksHandler):
             return None
 
     def read(self, request):
             return None
 
     def read(self, request):
+        key_sep = '$'
         search_string = request.GET.get('search')
         is_lektura = self.parse_bool(request.GET.get('lektura'))
         is_audiobook = self.parse_bool(request.GET.get('audiobook'))
         preview = self.parse_bool(request.GET.get('preview'))
 
         new_api = request.GET.get('new_api')
         search_string = request.GET.get('search')
         is_lektura = self.parse_bool(request.GET.get('lektura'))
         is_audiobook = self.parse_bool(request.GET.get('audiobook'))
         preview = self.parse_bool(request.GET.get('preview'))
 
         new_api = request.GET.get('new_api')
-        if new_api:
-            key_sep = ','
-        else:
-            key_sep = '$'
         after = request.GET.get('after')
         count = int(request.GET.get('count', 50))
         books = self.order_books(Book.objects.distinct(), new_api)
         after = request.GET.get('after')
         count = int(request.GET.get('count', 50))
         books = self.order_books(Book.objects.distinct(), new_api)
@@ -436,7 +425,7 @@ class AnonFilterBooksHandler(AnonymousBooksHandler):
             remaining_count = count - len(filtered_books)
             new_books = [
                 BookProxy(book, '%s%s%s' % (
             remaining_count = count - len(filtered_books)
             new_books = [
                 BookProxy(book, '%s%s%s' % (
-                    label, key_sep, book.slug if not new_api else self.full_sort_key(book)))
+                    label, key_sep, book.slug if not new_api else book.full_sort_key()))
                 for book in book_list[:remaining_count]]
             filtered_books += new_books
             if len(filtered_books) == count:
                 for book in book_list[:remaining_count]]
             filtered_books += new_books
             if len(filtered_books) == count:
@@ -514,50 +503,6 @@ def add_file_getters():
 add_file_getters()
 
 
 add_file_getters()
 
 
-class CollectionDetails(object):
-    """Custom Collection fields."""
-
-    @classmethod
-    def href(cls, collection):
-        """ Returns URI in the API for the collection. """
-
-        return API_BASE + reverse("api_collection", args=[collection.slug])
-
-    @classmethod
-    def url(cls, collection):
-        """ Returns URL on the site. """
-
-        return WL_BASE + collection.get_absolute_url()
-
-    @classmethod
-    def books(cls, collection):
-        return Book.objects.filter(collection.get_query())
-
-
-class CollectionDetailHandler(BaseHandler, CollectionDetails):
-    allowed_methods = ('GET',)
-    fields = ['url', 'title', 'description', 'books']
-
-    @piwik_track
-    def read(self, request, slug):
-        """ Returns details of a collection, identified by slug. """
-        try:
-            return Collection.objects.get(slug=slug)
-        except Collection.DoesNotExist:
-            return rc.NOT_FOUND
-
-
-class CollectionsHandler(BaseHandler, CollectionDetails):
-    allowed_methods = ('GET',)
-    model = Collection
-    fields = ['url', 'href', 'title']
-
-    @piwik_track
-    def read(self, request):
-        """ Returns all collections. """
-        return Collection.objects.all()
-
-
 class TagDetails(object):
     """Custom Tag fields."""
 
 class TagDetails(object):
     """Custom Tag fields."""
 
@@ -609,6 +554,7 @@ class TagsHandler(BaseHandler, TagDetails):
     def read(self, request, category=None, pk=None):
         """ Lists all tags in the category (eg. all themes). """
         if pk is not None:
     def read(self, request, category=None, pk=None):
         """ Lists all tags in the category (eg. all themes). """
         if pk is not None:
+            # FIXME: Unused?
             try:
                 return Tag.objects.exclude(category='set').get(pk=pk)
             except Book.DoesNotExist:
             try:
                 return Tag.objects.exclude(category='set').get(pk=pk)
             except Book.DoesNotExist:
@@ -733,7 +679,7 @@ class UserDataHandler(BaseHandler):
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
         if slug is None:
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
         if slug is None:
-            return {'username': request.user.username, 'premium': is_subscribed(request.user)}
+            return {'username': request.user.username, 'premium': user_is_subscribed(request.user)}
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
@@ -762,6 +708,7 @@ class UserDataHandler(BaseHandler):
 class UserShelfHandler(BookDetailHandler):
     fields = book_list_fields + ['liked']
 
 class UserShelfHandler(BookDetailHandler):
     fields = book_list_fields + ['liked']
 
+    # FIXME: Unused?
     def parse_bool(self, s):
         if s in ('true', 'false'):
             return s == 'true'
     def parse_bool(self, s):
         if s in ('true', 'false'):
             return s == 'true'