Update dep.
[wolnelektury.git] / src / api / fields.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from rest_framework import serializers
6 from sorl.thumbnail import default
7 from django.core.urlresolvers import reverse
8 from paypal.rest import user_is_subscribed
9
10
11 class AbsoluteURLField(serializers.ReadOnlyField):
12     def __init__(self, view_name=None, view_args=None, source='get_absolute_url', *args, **kwargs):
13         if view_name is not None:
14             source = '*'
15         super(AbsoluteURLField, self).__init__(*args, source=source, **kwargs)
16         self.view_name = view_name
17         self.view_args = {}
18         if view_args:
19             for v in view_args:
20                 fields = v.split(':', 1)
21                 self.view_args[fields[0]] = fields[1] if len(fields)>1 else fields[0]
22
23     def to_representation(self, value):
24         if self.view_name is not None:
25             kwargs = {
26                 arg: getattr(value, field)
27                 for (arg, field) in self.view_args.items()
28             }
29             value = reverse(self.view_name, kwargs=kwargs)
30         return self.context['request'].build_absolute_uri(value)
31
32
33 class LegacyMixin(object):
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:
39                 value[field] = ''
40         return value
41
42
43 class UserPremiumField(serializers.ReadOnlyField):
44     def __init__(self, *args, **kwargs):
45         super(UserPremiumField, self).__init__(*args, source='*', **kwargs)
46
47     def to_representation(self, value):
48         return user_is_subscribed(value)
49
50
51 class ThumbnailField(serializers.FileField):
52     def __init__(self, geometry, *args, **kwargs):
53         self.geometry = geometry
54         super(ThumbnailField, self).__init__(*args, **kwargs)
55
56     def to_representation(self, value):
57         if value:
58             return super(ThumbnailField, self).to_representation(
59                 default.backend.get_thumbnail(value, self.geometry)
60             )