api serves archive files by default.

This commit is contained in:
Jonas Winkler 2020-11-25 14:48:36 +01:00
parent 8069c2eb6a
commit 95ec520f13

View File

@ -1,3 +1,5 @@
import os
from django.db.models import Count, Max from django.db.models import Count, Max
from django.http import HttpResponse, HttpResponseBadRequest, Http404 from django.http import HttpResponse, HttpResponseBadRequest, Http404
from django.views.decorators.cache import cache_control from django.views.decorators.cache import cache_control
@ -126,15 +128,25 @@ class DocumentViewSet(RetrieveModelMixin,
index.remove_document_from_index(self.get_object()) index.remove_document_from_index(self.get_object())
return super(DocumentViewSet, self).destroy(request, *args, **kwargs) return super(DocumentViewSet, self).destroy(request, *args, **kwargs)
def file_response(self, pk, disposition): @staticmethod
doc = Document.objects.get(id=pk) def original_requested(request):
return (
'original' in request.query_params and
request.query_params['original'] == 'true'
)
if doc.storage_type == Document.STORAGE_TYPE_UNENCRYPTED: def file_response(self, pk, request, disposition):
doc = Document.objects.get(id=pk)
mime_type = doc.mime_type
if not self.original_requested(request) and os.path.isfile(doc.archive_path):
file_handle = doc.archive_file
mime_type = 'application/pdf'
elif doc.storage_type == Document.STORAGE_TYPE_UNENCRYPTED:
file_handle = doc.source_file file_handle = doc.source_file
else: else:
file_handle = GnuPG.decrypted(doc.source_file) file_handle = GnuPG.decrypted(doc.source_file)
response = HttpResponse(file_handle, content_type=doc.mime_type) response = HttpResponse(file_handle, content_type=mime_type)
response["Content-Disposition"] = '{}; filename="{}"'.format( response["Content-Disposition"] = '{}; filename="{}"'.format(
disposition, doc.file_name) disposition, doc.file_name)
return response return response
@ -152,7 +164,8 @@ class DocumentViewSet(RetrieveModelMixin,
@action(methods=['get'], detail=True) @action(methods=['get'], detail=True)
def preview(self, request, pk=None): def preview(self, request, pk=None):
try: try:
response = self.file_response(pk, "inline") response = self.file_response(
pk, request, "inline")
return response return response
except FileNotFoundError: except FileNotFoundError:
raise Http404("Document source file does not exist") raise Http404("Document source file does not exist")
@ -169,7 +182,8 @@ class DocumentViewSet(RetrieveModelMixin,
@action(methods=['get'], detail=True) @action(methods=['get'], detail=True)
def download(self, request, pk=None): def download(self, request, pk=None):
try: try:
return self.file_response(pk, "attachment") return self.file_response(
pk, request, "attachment")
except FileNotFoundError: except FileNotFoundError:
raise Http404("Document source file does not exist") raise Http404("Document source file does not exist")