import mimetypes
import posixpath

from django.core.exceptions import SuspiciousFileOperation
from django.core.files.storage import default_storage
from django.http import FileResponse, Http404


def media_proxy(request, path):
    normalized_path = posixpath.normpath(path).lstrip("/")
    if (
        not normalized_path
        or normalized_path == "."
        or normalized_path.startswith("../")
        or path.startswith("/")
    ):
        raise SuspiciousFileOperation("Invalid media path")

    try:
        file_obj = default_storage.open(normalized_path, "rb")
    except FileNotFoundError as exc:
        raise Http404("Media file not found") from exc

    content_type, _ = mimetypes.guess_type(normalized_path)
    return FileResponse(file_obj, content_type=content_type)
