diff --git a/django_etesync/serializers.py b/django_etesync/serializers.py index 6a495bf..5946293 100644 --- a/django_etesync/serializers.py +++ b/django_etesync/serializers.py @@ -60,6 +60,19 @@ class CollectionContentField(BinaryBase64Field): return None +class ChunksField(serializers.RelatedField): + def to_representation(self, obj): + prefer_inline = self.context.get('prefer_inline', False) + if prefer_inline: + with open(obj.chunkFile.path, 'rb') as f: + return (obj.uid, b64encode(f.read())) + else: + return (obj.uid, ) + + def to_internal_value(self, data): + return (data[0], b64decode(data[1])) + + class CollectionItemChunkSerializer(serializers.ModelSerializer): class Meta: model = models.CollectionItemChunk @@ -67,55 +80,15 @@ class CollectionItemChunkSerializer(serializers.ModelSerializer): class CollectionItemRevisionSerializer(serializers.ModelSerializer): - chunks = serializers.SlugRelatedField( - slug_field='uid', + chunks = ChunksField( queryset=models.CollectionItemChunk.objects.all(), many=True ) - chunksUrls = serializers.SerializerMethodField('get_chunks_urls') - chunksData = serializers.SerializerMethodField('get_chunks_data') meta = BinaryBase64Field() class Meta: model = models.CollectionItemRevision - fields = ('chunks', 'meta', 'uid', 'deleted', 'chunksUrls', 'chunksData') - - # FIXME: currently the user is exposed in the url. We don't want that, and we can probably avoid that but still - # save it under the user. - # We would probably be better off just let the user calculate the urls from the uid and a base url for the snapshot. - # E.g. chunkBaseUrl: "/media/bla/bla/" or chunkBaseUrl: "https://media.etesync.com/bla/bla" - def get_chunks_urls(self, obj): - prefer_inline = self.context.get('prefer_inline', False) - if prefer_inline: - return None - - ret = [] - for chunk in obj.chunks.all(): - ret.append(chunk.chunkFile.url) - - return ret - - def get_chunks_data(self, obj): - prefer_inline = self.context.get('prefer_inline', False) - if not prefer_inline: - return None - - ret = [] - for chunk in obj.chunks.all(): - with open(chunk.chunkFile.path, 'rb') as f: - ret.append(b64encode(f.read())) - - return ret - - def to_representation(self, instance): - ret = super().to_representation(instance) - prefer_inline = self.context.get('prefer_inline', False) - if prefer_inline: - ret.pop('chunksUrls') - else: - ret.pop('chunksData') - - return ret + fields = ('chunks', 'meta', 'uid', 'deleted') class CollectionItemSerializer(serializers.ModelSerializer):