fix
[wolnelektury.git] / src / api / handlers.py
index 8d32873..3aefcff 100644 (file)
@@ -30,7 +30,7 @@ from wolnelektury.utils import re_escape
 from . import emitters  # Register our emitters
 
 API_BASE = WL_BASE = MEDIA_BASE = lazy(
 from . import emitters  # Register our emitters
 
 API_BASE = WL_BASE = MEDIA_BASE = lazy(
-    lambda: u'http://' + Site.objects.get_current().domain, unicode)()
+    lambda: u'https://' + Site.objects.get_current().domain, unicode)()
 
 
 category_singular = {
 
 
 category_singular = {
@@ -47,6 +47,9 @@ for k, v in category_singular.items():
 
 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
 
 
 book_tag_categories = ['author', 'epoch', 'kind', 'genre']
 
+book_list_fields = book_tag_categories + [
+    'href', 'title', 'url', 'cover', 'cover_thumb', 'slug', 'simple_thumb', 'has_audio', 'cover_color']
+
 
 def read_tags(tags, request, allowed):
     """ Reads a path of filtering tags.
 
 def read_tags(tags, request, allowed):
     """ Reads a path of filtering tags.
@@ -161,7 +164,7 @@ class BookDetails(object):
 
     @classmethod
     def cover_color(cls, book):
 
     @classmethod
     def cover_color(cls, book):
-        return WLCover.epoch_colors.get(book.extra_info['epoch'], '#000000')
+        return WLCover.epoch_colors.get(book.extra_info.get('epoch'), '#000000')
 
 
 class BookDetailHandler(BaseHandler, BookDetails):
 
 
 class BookDetailHandler(BaseHandler, BookDetails):
@@ -191,8 +194,7 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
     """
     allowed_methods = ('GET',)
     model = Book
     """
     allowed_methods = ('GET',)
     model = Book
-    fields = book_tag_categories + [
-        'href', 'title', 'url', 'cover', 'cover_thumb', 'slug', 'simple_thumb', 'has_audio', 'cover_color']
+    fields = book_list_fields
 
     @classmethod
     def genres(cls, book):
 
     @classmethod
     def genres(cls, book):
@@ -202,7 +204,7 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
     @piwik_track
     def read(self, request, tags=None, top_level=False, audiobooks=False, daisy=False, pk=None,
              recommended=False, newest=False, books=None,
     @piwik_track
     def read(self, request, tags=None, top_level=False, audiobooks=False, daisy=False, pk=None,
              recommended=False, newest=False, books=None,
-             after=None, before=None, count=None):
+             after=None, count=None):
         """ Lists all books with given tags.
 
         :param tags: filtering tags; should be a path of categories
         """ Lists all books with given tags.
 
         :param tags: filtering tags; should be a path of categories
@@ -224,8 +226,6 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
 
         if 'after' in request.GET:
             after = request.GET['after']
 
         if 'after' in request.GET:
             after = request.GET['after']
-        if 'before' in request.GET:
-            before = request.GET['before']
         if 'count' in request.GET:
             count = request.GET['count']
 
         if 'count' in request.GET:
             count = request.GET['count']
 
@@ -250,20 +250,16 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
         if newest:
             books = books.order_by('-created_at')
 
         if newest:
             books = books.order_by('-created_at')
 
+        # beznadzieja
         if after:
             books = books.filter(slug__gt=after)
         if after:
             books = books.filter(slug__gt=after)
-        if before:
-            books = books.filter(slug__lt=before)
 
         books = books.only('slug', 'title', 'cover', 'cover_thumb')
         for category in book_tag_categories:
             books = prefetch_relations(books, category)
 
         if count:
 
         books = books.only('slug', 'title', 'cover', 'cover_thumb')
         for category in book_tag_categories:
             books = prefetch_relations(books, category)
 
         if count:
-            if before:
-                books = list(reversed(books.order_by('-slug')[:count]))
-            else:
-                books = books[:count]
+            books = books[:count]
 
         return books
 
 
         return books
 
@@ -274,9 +270,23 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
 class BooksHandler(BookDetailHandler):
     allowed_methods = ('GET', 'POST')
     model = Book
 class BooksHandler(BookDetailHandler):
     allowed_methods = ('GET', 'POST')
     model = Book
-    fields = book_tag_categories + ['href', 'title', 'url', 'cover', 'cover_thumb', 'cover_color', 'slug']
+    fields = book_list_fields + ['liked']
     anonymous = AnonymousBooksHandler
 
     anonymous = AnonymousBooksHandler
 
+    # hack, because piston is stupid
+    @classmethod
+    def liked(cls, book):
+        return getattr(book, 'liked', None)
+
+    def read(self, request, **kwargs):
+        books = AnonymousBooksHandler().read(request, **kwargs)
+        likes = set(Book.tagged.with_any(request.user.tag_set.all()).values_list('id', flat=True))
+
+        new_books = [
+            BookProxy(book).set('liked', book.id in likes)
+            for book in books]
+        return QuerySetProxy(new_books)
+
     def create(self, request, *args, **kwargs):
         if not request.user.has_perm('catalogue.add_book'):
             return rc.FORBIDDEN
     def create(self, request, *args, **kwargs):
         if not request.user.has_perm('catalogue.add_book'):
             return rc.FORBIDDEN
@@ -310,15 +320,16 @@ class BookProxy(models.Model):
     class Meta:
         managed = False
 
     class Meta:
         managed = False
 
-    def __init__(self, book, key):
+    def __init__(self, book, key=None):
         self.book = book
         self.key = key
 
         self.book = book
         self.key = key
 
+    def set(self, attr, value):
+        self.__setattr__(attr, value)
+        return self
+
     def __getattr__(self, item):
     def __getattr__(self, item):
-        if item not in ('book', 'key'):
-            return self.book.__getattribute__(item)
-        else:
-            return self.__getattribute__(item)
+        return self.book.__getattribute__(item)
 
 
 class QuerySetProxy(models.QuerySet):
 
 
 class QuerySetProxy(models.QuerySet):
@@ -329,9 +340,8 @@ class QuerySetProxy(models.QuerySet):
         return iter(self.list)
 
 
         return iter(self.list)
 
 
-class FilterBooksHandler(AnonymousBooksHandler):
-    fields = book_tag_categories + [
-        'href', 'title', 'url', 'cover', 'cover_thumb', 'cover_color', 'simple_thumb', 'has_audio', 'slug', 'key']
+class AnonFilterBooksHandler(AnonymousBooksHandler):
+    fields = book_list_fields + ['key']
 
     def parse_bool(self, s):
         if s in ('true', 'false'):
 
     def parse_bool(self, s):
         if s in ('true', 'false'):
@@ -401,7 +411,26 @@ class FilterBooksHandler(AnonymousBooksHandler):
         return QuerySetProxy(filtered_books)
 
 
         return QuerySetProxy(filtered_books)
 
 
+class FilterBooksHandler(BooksHandler):
+    anonymous = AnonFilterBooksHandler
+    fields = book_list_fields + ['key', 'liked']
+
+    # hack, because piston is stupid
+    @classmethod
+    def liked(cls, book):
+        return getattr(book, 'liked', None)
+
+    def read(self, request):
+        qsp = AnonFilterBooksHandler().read(request)
+        likes = set(Book.tagged.with_any(request.user.tag_set.all()).values_list('id', flat=True))
+        for book in qsp.list:
+            book.set('liked', book.id in likes)
+        return qsp
+
+
 class BookPreviewHandler(BookDetailHandler):
 class BookPreviewHandler(BookDetailHandler):
+    fields = BookDetailHandler.fields + ['slug']
+
     def read(self, request):
         return Book.objects.filter(preview=True)
 
     def read(self, request):
         return Book.objects.filter(preview=True)
 
@@ -557,7 +586,6 @@ class TagsHandler(BaseHandler, TagDetails):
             return rc.NOT_FOUND
 
         after = request.GET.get('after')
             return rc.NOT_FOUND
 
         after = request.GET.get('after')
-        before = request.GET.get('before')
         count = request.GET.get('count')
 
         tags = Tag.objects.filter(category=category_sng).exclude(items=None).order_by('slug')
         count = request.GET.get('count')
 
         tags = Tag.objects.filter(category=category_sng).exclude(items=None).order_by('slug')
@@ -571,14 +599,9 @@ class TagsHandler(BaseHandler, TagDetails):
 
         if after:
             tags = tags.filter(slug__gt=after)
 
         if after:
             tags = tags.filter(slug__gt=after)
-        if before:
-            tags = tags.filter(slug__lt=before)
 
         if count:
 
         if count:
-            if before:
-                tags = list(reversed(tags.order_by('-slug')[:count]))
-            else:
-                tags = tags[:count]
+            tags = tags[:count]
 
         return tags
 
 
         return tags
 
@@ -669,14 +692,14 @@ class PictureHandler(BaseHandler):
 
 class UserDataHandler(BaseHandler):
     model = BookUserData
 
 class UserDataHandler(BaseHandler):
     model = BookUserData
-    fields = ('state', 'username')
+    fields = ('state', 'username', 'premium')
     allowed_methods = ('GET', 'POST')
 
     def read(self, request, slug=None):
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
         if slug is None:
     allowed_methods = ('GET', 'POST')
 
     def read(self, request, slug=None):
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
         if slug is None:
-            return {'username': request.user.username}
+            return {'username': request.user.username, 'premium': is_subscribed(request.user)}
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
@@ -703,8 +726,7 @@ class UserDataHandler(BaseHandler):
 
 
 class UserShelfHandler(BookDetailHandler):
 
 
 class UserShelfHandler(BookDetailHandler):
-    fields = book_tag_categories + [
-        'href', 'title', 'url', 'cover', 'cover_thumb', 'simple_thumb', 'slug', 'key']
+    fields = book_list_fields + ['liked']
 
     def parse_bool(self, s):
         if s in ('true', 'false'):
 
     def parse_bool(self, s):
         if s in ('true', 'false'):
@@ -712,9 +734,15 @@ class UserShelfHandler(BookDetailHandler):
         else:
             return None
 
         else:
             return None
 
+    # hack, because piston is stupid
+    @classmethod
+    def liked(cls, book):
+        return getattr(book, 'liked', None)
+
     def read(self, request, state):
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
     def read(self, request, state):
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
+        likes = set(Book.tagged.with_any(request.user.tag_set.all()).values_list('id', flat=True))
         if state not in ('reading', 'complete', 'likes'):
             return rc.NOT_FOUND
         after = request.GET.get('after')
         if state not in ('reading', 'complete', 'likes'):
             return rc.NOT_FOUND
         after = request.GET.get('after')
@@ -729,7 +757,10 @@ class UserShelfHandler(BookDetailHandler):
             books = books.filter(slug__gt=after)
         if count:
             books = books[:count]
             books = books.filter(slug__gt=after)
         if count:
             books = books[:count]
-        return books
+        new_books = []
+        for book in books:
+            new_books.append(BookProxy(book).set('liked', book.id in likes))
+        return QuerySetProxy(new_books)
 
 
 class UserLikeHandler(BaseHandler):
 
 
 class UserLikeHandler(BaseHandler):
@@ -745,13 +776,14 @@ class UserLikeHandler(BaseHandler):
             return rc.NOT_FOUND
         return {'likes': likes(request.user, book)}
 
             return rc.NOT_FOUND
         return {'likes': likes(request.user, book)}
 
-    def create(self, request, slug, action='like'):
+    def create(self, request, slug):
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
             return rc.NOT_FOUND
         if not request.user.is_authenticated():
             return rc.FORBIDDEN
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
             return rc.NOT_FOUND
+        action = request.GET.get('action', 'like')
         if action == 'like':
             book.like(request.user)
         elif action == 'unlike':
         if action == 'like':
             book.like(request.user)
         elif action == 'unlike':
@@ -761,7 +793,8 @@ class UserLikeHandler(BaseHandler):
 
 class BlogEntryHandler(BaseHandler):
     model = Entry
 
 class BlogEntryHandler(BaseHandler):
     model = Entry
-    fields = ('title', 'lead', 'body', 'place', 'time', 'image_url', 'gallery_urls', 'type', 'key')
+    fields = (
+        'title', 'lead', 'body', 'place', 'time', 'image_url', 'image_thumb', 'gallery_urls', 'type', 'key', 'url')
 
     def read(self, request):
         after = request.GET.get('after')
 
     def read(self, request):
         after = request.GET.get('after')
@@ -775,12 +808,21 @@ class BlogEntryHandler(BaseHandler):
 
     @classmethod
     def image_url(cls, entry):
 
     @classmethod
     def image_url(cls, entry):
-        return entry.image.url if entry.image else None
+        return (WL_BASE + entry.image.url) if entry.image else None
+
+    @classmethod
+    def image_thumb(cls, entry):
+        return MEDIA_BASE + default.backend.get_thumbnail(
+            entry.image, "193x193").url if entry.image else ''
 
     @classmethod
     def gallery_urls(cls, entry):
 
     @classmethod
     def gallery_urls(cls, entry):
-        return [photo.url() for photo in entry.photo_set.all()]
+        return [WL_BASE + photo.url() for photo in entry.photo_set.all()]
 
     @classmethod
     def key(cls, entry):
         return entry.first_published_at
 
     @classmethod
     def key(cls, entry):
         return entry.first_published_at
+
+    @classmethod
+    def url(cls, entry):
+        return WL_BASE + entry.get_absolute_url()