56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
# fargo - document box
|
|
# Copyright (C) 2016-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
|
|
import uuid
|
|
|
|
from django.core.files.base import ContentFile
|
|
from rest_framework import fields, serializers
|
|
|
|
from . import api_errors
|
|
|
|
|
|
class SlugCreatedRelatedField(serializers.SlugRelatedField):
|
|
def to_internal_value(self, data):
|
|
return self.get_queryset().get_or_create(**{self.slug_field: data})[0]
|
|
|
|
|
|
class Base64FileField(fields.Field):
|
|
def __init__(self, *args, **kwargs):
|
|
self.max_size = kwargs.pop('max_size', 0)
|
|
super().__init__(*args, **kwargs)
|
|
|
|
def get_max_size(self):
|
|
if hasattr(self.max_size, '__call__'):
|
|
return self.max_size()
|
|
return self.max_size
|
|
|
|
def to_internal_value(self, data):
|
|
if isinstance(data, str):
|
|
# base64 encoded image - decode
|
|
name = uuid.uuid4()
|
|
try:
|
|
content = base64.b64decode(data)
|
|
except ValueError:
|
|
raise api_errors.APIError('NOT_BASE64')
|
|
max_size = self.get_max_size()
|
|
if max_size and len(content) > self.get_max_size():
|
|
raise api_errors.APIError('TOO_BIG', limit=str(self.get_max_size()))
|
|
data = ContentFile(content, name=name)
|
|
else:
|
|
raise api_errors.APIError('NOT_STRING')
|
|
return data
|