1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from rest_framework import serializers
5 from sorl.thumbnail import default
6 from rest_framework.reverse import reverse
7 from club.models import Membership
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:
14 super(AbsoluteURLField, self).__init__(*args, source=source, **kwargs)
15 self.view_name = view_name
19 fields = v.split(':', 1)
20 self.view_args[fields[0]] = fields[1] if len(fields) > 1 else fields[0]
22 def to_representation(self, value):
23 request = self.context['request']
24 if self.view_name is not None:
26 arg: getattr(value, field)
27 for (arg, field) in self.view_args.items()
29 return reverse(self.view_name, kwargs=kwargs, request=request)
30 return request.build_absolute_uri(value)
34 def to_representation(self, value):
35 value = super(LegacyMixin, self).to_representation(value)
36 non_null_fields = getattr(getattr(self, 'Meta', None), 'legacy_non_null_fields', [])
37 for field in non_null_fields:
38 if field in value and value[field] is None:
43 class UserPremiumField(serializers.ReadOnlyField):
44 def __init__(self, *args, **kwargs):
45 super(UserPremiumField, self).__init__(*args, source='*', **kwargs)
47 def to_representation(self, value):
48 return Membership.is_active_for(value)
51 class ThumbnailField(serializers.FileField):
52 def __init__(self, geometry, *args, **kwargs):
53 self.geometry = geometry
54 super(ThumbnailField, self).__init__(*args, **kwargs)
56 def to_representation(self, value):
58 return super(ThumbnailField, self).to_representation(
59 default.backend.get_thumbnail(value, self.geometry)