summaryrefslogtreecommitdiffstats
path: root/combo/apps/assets/api_views.py
blob: 07f2da223f1c458a63d957fe7970175162a69331 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# combo - content management system
# Copyright (C) 2019  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import base64

from django.core.files import File
from django.utils.six import BytesIO

from rest_framework import serializers, permissions, status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from .models import Asset


class FileSerializer(serializers.Serializer):
    content = serializers.CharField(required=True, allow_blank=False)
    content_type = serializers.CharField(required=False, allow_null=True)
    filename = serializers.CharField(required=False, allow_null=True)


class AssetSerializer(serializers.Serializer):
    asset = FileSerializer(required=True)


class Set(GenericAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = AssetSerializer

    def post(self, request, key, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            response = {'err': 1, 'err_desc': serializer.errors}
            return Response(response, status.HTTP_400_BAD_REQUEST)
        data = serializer.validated_data

        asset, created = Asset.objects.get_or_create(key=key)
        asset.asset = File(
            BytesIO(base64.decodestring(data['asset']['content'].encode('ascii'))),
            name=data['asset'].get('filename'))
        asset.save()
        response = {'err': 0}
        return Response(response)

view_set = Set.as_view()