OpenSlides/openslides/mediafiles/serializers.py

72 lines
2.2 KiB
Python
Raw Normal View History

import mimetypes
from django.conf import settings
from django.db import models as dbmodels
from PyPDF2 import PdfFileReader
2016-11-18 09:40:36 +01:00
from PyPDF2.utils import PdfReadError
from .models import Mediafile
from ..utils.rest_api import FileField, ModelSerializer, SerializerMethodField
class AngularCompatibleFileField(FileField):
def to_internal_value(self, data):
2019-01-06 16:22:33 +01:00
if data == "":
return None
return super(AngularCompatibleFileField, self).to_internal_value(data)
def to_representation(self, value):
if value is None:
return None
filetype = mimetypes.guess_type(value.path)[0]
2019-01-06 16:22:33 +01:00
result = {"name": value.name, "type": filetype}
if filetype == "application/pdf":
try:
2019-01-06 16:22:33 +01:00
result["pages"] = PdfFileReader(open(value.path, "rb")).getNumPages()
except FileNotFoundError:
# File was deleted from server. Set 'pages' to 0.
2019-01-06 16:22:33 +01:00
result["pages"] = 0
2016-11-18 09:40:36 +01:00
except PdfReadError:
# File could be encrypted but not be detected by PyPDF.
2019-01-06 16:22:33 +01:00
result["pages"] = 0
result["encrypted"] = True
return result
class MediafileSerializer(ModelSerializer):
"""
Serializer for mediafile.models.Mediafile objects.
"""
2019-01-06 16:22:33 +01:00
media_url_prefix = SerializerMethodField()
filesize = SerializerMethodField()
def __init__(self, *args, **kwargs):
"""
This constructor overwrites the FileField field serializer to return the file meta data in a way that the
angualarjs upload module likes
"""
super(MediafileSerializer, self).__init__(*args, **kwargs)
self.serializer_field_mapping[dbmodels.FileField] = AngularCompatibleFileField
2016-01-24 22:58:45 +01:00
if self.instance is not None:
2019-01-06 16:22:33 +01:00
self.fields["mediafile"].read_only = True
class Meta:
model = Mediafile
fields = (
2019-01-06 16:22:33 +01:00
"id",
"title",
"mediafile",
"media_url_prefix",
"uploader",
"filesize",
"hidden",
"timestamp",
)
def get_filesize(self, mediafile):
return mediafile.get_filesize()
def get_media_url_prefix(self, mediafile):
return settings.MEDIA_URL