import os from django.conf import settings from django.shortcuts import get_object_or_404 from django.http import HttpResponse, FileResponse from sorl.thumbnail import get_thumbnail from .models import PostFileModel def serve_content_file(request, file_hash): """ View function to serve content files for download or inline viewing """ print(f"Requesting file: {file_hash}") download = request.GET.get("d") thumbnail = request.GET.get("t") try: obj_file = get_object_or_404(PostFileModel, hash_blake3=file_hash) file_name = obj_file.name.first().filename file_type = obj_file.file_type source_file = obj_file.file if thumbnail: if file_type != "image": source_file = obj_file.thumbnail if thumbnail == "sx": file_name += ".thumb_64.jpg" thumbnail_file = get_thumbnail(source_file.path, "64", upscale=False) file = open( os.path.abspath(os.path.join(settings.MEDIA_ROOT, thumbnail_file.name)), "rb", ) elif thumbnail == "sm": file_name += ".thumb_256.jpg" thumbnail_file = get_thumbnail(source_file.path, "256", upscale=False) file = open( os.path.abspath(os.path.join(settings.MEDIA_ROOT, thumbnail_file.name)), "rb", ) elif thumbnail == "md": file_name += ".thumb_748.jpg" thumbnail_file = get_thumbnail(source_file.path, "748", upscale=False) file = open( os.path.abspath(os.path.join(settings.MEDIA_ROOT, thumbnail_file.name)), "rb", ) elif thumbnail == "lg": file_name += ".thumb_1024.jpg" thumbnail_file = get_thumbnail(source_file.path, "1024", upscale=False) file = open( os.path.abspath(os.path.join(settings.MEDIA_ROOT, thumbnail_file.name)), "rb", ) elif thumbnail == "xl": file_name += ".thumb_2048.jpg" thumbnail_file = get_thumbnail(source_file.path, "2048", upscale=False) file = open( os.path.abspath(os.path.join(settings.MEDIA_ROOT, thumbnail_file.name)), "rb", ) else: file = source_file.file response = FileResponse(file) if download == "1": response["Content-Disposition"] = f'attachment; filename="{file_name}"' else: response["Content-Disposition"] = f'inline; filename="{file_name}"' return response except Exception as e: print(f"Error serving file: {e}") return HttpResponse("File not found", status=404)