371da38ad1e772e0a131dccf27608f967cac8ae9
[wolnelektury.git] / src / catalogue / api / fields.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from rest_framework import serializers
5 from api.fields import AbsoluteURLField
6 from catalogue.models import Book
7 from club.models import Membership
8
9
10 class BookLiked(serializers.ReadOnlyField):
11     def __init__(self, source='pk', **kwargs):
12         super(BookLiked, self).__init__(source=source, **kwargs)
13
14     def to_representation(self, value):
15         request = self.context['request']
16         if not hasattr(request, 'liked_books'):
17             if request.user.is_authenticated():
18                 request.liked_books = set(Book.tagged.with_any(request.user.tag_set.all()).values_list('id', flat=True))
19             else:
20                 request.liked_books = None
21         if request.liked_books is not None:
22             return value in request.liked_books
23
24
25 class EmbargoURLField(AbsoluteURLField):
26     def to_representation(self, value):
27         request = self.context['request']
28         # FIXME: See #3955.
29         if True or Membership.is_active_for(request.user):
30             return super().to_representation(value)
31         else:
32             return None