update requirements
[wolnelektury.git] / src / api / handlers.py
index c899976..2a12ec4 100644 (file)
@@ -9,6 +9,7 @@ from django.core.urlresolvers import reverse
 from django.http.response import HttpResponse
 from django.utils.functional import lazy
 from django.db import models
+from migdal.models import Entry
 from piston.handler import AnonymousBaseHandler, BaseHandler
 from piston.utils import rc
 from sorl.thumbnail import default
@@ -18,8 +19,10 @@ 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 picture.models import Picture
 from picture.forms import PictureImportForm
+from social.utils import likes
 
 from stats.utils import piwik_track
 from wolnelektury.utils import re_escape
@@ -27,7 +30,7 @@ from wolnelektury.utils import re_escape
 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 = {
@@ -44,6 +47,9 @@ for k, v in category_singular.items():
 
 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.
@@ -156,6 +162,10 @@ class BookDetails(object):
     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')
+
 
 class BookDetailHandler(BaseHandler, BookDetails):
     """ Main handler for Book objects.
@@ -164,7 +174,8 @@ class BookDetailHandler(BaseHandler, BookDetails):
     """
     allowed_methods = ['GET']
     fields = ['title', 'parent', 'children'] + Book.formats + [
-        'media', 'url', 'cover', 'cover_thumb', 'simple_thumb', 'simple_cover', 'fragment_data', 'preview'] + [
+        'media', 'url', 'cover', 'cover_thumb', 'simple_thumb', 'simple_cover', 'fragment_data', 'audio_length',
+        'preview', 'cover_color'] + [
             category_plural[c] for c in book_tag_categories]
 
     @piwik_track
@@ -183,7 +194,7 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
     """
     allowed_methods = ('GET',)
     model = Book
-    fields = book_tag_categories + ['href', 'title', 'url', 'cover', 'cover_thumb', 'slug', 'simple_thumb']
+    fields = book_list_fields
 
     @classmethod
     def genres(cls, book):
@@ -265,9 +276,23 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails):
 class BooksHandler(BookDetailHandler):
     allowed_methods = ('GET', 'POST')
     model = Book
-    fields = book_tag_categories + ['href', 'title', 'url', 'cover', 'cover_thumb', 'slug']
+    fields = book_list_fields + ['liked']
     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
@@ -301,15 +326,16 @@ class BookProxy(models.Model):
     class Meta:
         managed = False
 
-    def __init__(self, book, key):
+    def __init__(self, book, key=None):
         self.book = book
         self.key = key
 
+    def set(self, attr, value):
+        self.__setattr__(attr, value)
+        return self
+
     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):
@@ -320,9 +346,8 @@ class QuerySetProxy(models.QuerySet):
         return iter(self.list)
 
 
-class FilterBooksHandler(AnonymousBooksHandler):
-    fields = book_tag_categories + [
-        'href', 'title', 'url', 'cover', 'cover_thumb', 'simple_thumb', 'slug', 'key']
+class AnonFilterBooksHandler(AnonymousBooksHandler):
+    fields = book_list_fields + ['key']
 
     def parse_bool(self, s):
         if s in ('true', 'false'):
@@ -392,6 +417,30 @@ class FilterBooksHandler(AnonymousBooksHandler):
         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):
+    fields = BookDetailHandler.fields + ['slug']
+
+    def read(self, request):
+        return Book.objects.filter(preview=True)
+
+
 # add categorized tags fields for Book
 def _tags_getter(category):
     @classmethod
@@ -433,6 +482,7 @@ def add_file_getters():
     for book_format in Book.formats:
         setattr(BookDetails, book_format, _file_getter(book_format))
 
+
 add_file_getters()
 
 
@@ -624,7 +674,7 @@ class FragmentsHandler(BaseHandler, FragmentDetails):
 
         """
         try:
-            tags, ancestors = read_tags(tags, allowed=self.categories)
+            tags, ancestors = read_tags(tags, request, allowed=self.categories)
         except ValueError:
             return rc.NOT_FOUND
         fragments = Fragment.tagged.with_all(tags).select_related('book')
@@ -654,16 +704,18 @@ class PictureHandler(BaseHandler):
 
 class UserDataHandler(BaseHandler):
     model = BookUserData
-    fields = ('state',)
+    fields = ('state', 'username', 'premium')
     allowed_methods = ('GET', 'POST')
 
-    def read(self, request, slug):
+    def read(self, request, slug=None):
+        if not request.user.is_authenticated():
+            return rc.FORBIDDEN
+        if slug is None:
+            return {'username': request.user.username, 'premium': is_subscribed(request.user)}
         try:
             book = Book.objects.get(slug=slug)
         except Book.DoesNotExist:
             return rc.NOT_FOUND
-        if not request.user.is_authenticated():
-            return rc.FORBIDDEN
         try:
             data = BookUserData.objects.get(book=book, user=request.user)
         except BookUserData.DoesNotExist:
@@ -686,8 +738,7 @@ class UserDataHandler(BaseHandler):
 
 
 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'):
@@ -695,17 +746,95 @@ class UserShelfHandler(BookDetailHandler):
         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
-        if state not in ('reading', 'complete'):
+        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')
         count = int(request.GET.get('count', 50))
-        ids = BookUserData.objects.filter(user=request.user, complete=state == 'complete').values_list('book_id', flat=True)
-        books = Book.objects.filter(id__in=list(ids)).distinct().order_by('slug')
+        if state == 'likes':
+            books = Book.tagged.with_any(request.user.tag_set.all())
+        else:
+            ids = BookUserData.objects.filter(user=request.user, complete=state == 'complete')\
+                .values_list('book_id', flat=True)
+            books = Book.objects.filter(id__in=list(ids)).distinct().order_by('slug')
         if after:
             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):
+    fields = []
+    allowed_methods = ('GET', 'POST')
+
+    def read(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
+        return {'likes': likes(request.user, book)}
+
+    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
+        action = request.GET.get('action', 'like')
+        if action == 'like':
+            book.like(request.user)
+        elif action == 'unlike':
+            book.unlike(request.user)
+        return {}
+
+
+class BlogEntryHandler(BaseHandler):
+    model = Entry
+    fields = (
+        'title', 'lead', 'body', 'place', 'time', 'image_url', 'image_thumb', 'gallery_urls', 'type', 'key', 'url')
+
+    def read(self, request):
+        after = request.GET.get('after')
+        count = int(request.GET.get('count', 20))
+        entries = Entry.published_objects.filter(in_stream=True).order_by('-first_published_at')
+        if after:
+            entries = entries.filter(first_published_at__lt=after)
+        if count:
+            entries = entries[:count]
+        return entries
+
+    @classmethod
+    def image_url(cls, entry):
+        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):
+        return [WL_BASE + photo.url() for photo in entry.photo_set.all()]
+
+    @classmethod
+    def key(cls, entry):
+        return entry.first_published_at
+
+    @classmethod
+    def url(cls, entry):
+        return WL_BASE + entry.get_absolute_url()