from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.views import View
from django.views.static import serve


class MediaView(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        _username = kwargs.get("username")
        _path = kwargs.get("path")
        if request.user.get_username() != _username:
            raise PermissionDenied

        if settings.DEBUG:
            return serve(request, f"user/{_username}/{_path}", settings.MEDIA_ROOT)

        _res = HttpResponse()
        _res["Content-Type"] = ""
        _res["X-Accel-Redirect"] = f"/internal/media/user/{_username}/{_path}"
        return _res
