Bugfix for player.
[wolnelektury.git] / src / 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 sorl.thumbnail import default
6 from django.urls import reverse
7 from club.models import Membership
8
9
10 class AbsoluteURLField(serializers.ReadOnlyField):
11     def __init__(self, view_name=None, view_args=None, source='get_absolute_url', *args, **kwargs):
12         if view_name is not None:
13             source = '*'
14         super(AbsoluteURLField, self).__init__(*args, source=source, **kwargs)
15         self.view_name = view_name
16         self.view_args = {}
17         if view_args:
18             for v in view_args:
19                 fields = v.split(':', 1)
20                 self.view_args[fields[0]] = fields[1] if len(fields) > 1 else fields[0]
21
22     def to_representation(self, value):
23         if self.view_name is not None:
24             kwargs = {
25                 arg: getattr(value, field)
26                 for (arg, field) in self.view_args.items()
27             }
28             value = reverse(self.view_name, kwargs=kwargs)
29         return self.context['request'].build_absolute_uri(value)
30
31
32 class LegacyMixin:
33     def to_representation(self, value):
34         value = super(LegacyMixin, self).to_representation(value)
35         non_null_fields = getattr(getattr(self, 'Meta', None), 'legacy_non_null_fields', [])
36         for field in non_null_fields:
37             if field in value and value[field] is None:
38                 value[field] = ''
39         return value
40
41
42 class UserPremiumField(serializers.ReadOnlyField):
43     def __init__(self, *args, **kwargs):
44         super(UserPremiumField, self).__init__(*args, source='*', **kwargs)
45
46     def to_representation(self, value):
47         return Membership.is_active_for(value)
48
49
50 class ThumbnailField(serializers.FileField):
51     def __init__(self, geometry, *args, **kwargs):
52         self.geometry = geometry
53         super(ThumbnailField, self).__init__(*args, **kwargs)
54
55     def to_representation(self, value):
56         if value:
57             return super(ThumbnailField, self).to_representation(
58                 default.backend.get_thumbnail(value, self.geometry)
59             )