diff --git a/review/views.py b/review/views.py index 98770f9..9e81e7c 100644 --- a/review/views.py +++ b/review/views.py @@ -1,4 +1,5 @@ import datetime +from io import BytesIO import logging import json import shutil @@ -630,6 +631,8 @@ class dolos_proxy_view(View): upstream_url = 'https://dolos.cs.aalto.fi' def dispatch(self, request, path): + local_static_directory = path + # Rewrite the URL: prepend the path with the upstream URL base_url = f'{self.upstream_url}/{path}' @@ -645,39 +648,43 @@ def dispatch(self, request, path): 'content-length': str(len(request.body)), }) - # Prepare the files files = [(field_name, file) for (field_name, file) in request.FILES.items()] + # If the path starts with 'static', download and save the file + if path.startswith('static') or path.startswith('assets') or path.startswith('api'): + local_file_path = os.path.join(settings.STATIC_ROOT, "/dolos-proxy", local_static_directory) + + print("LOCALFILEPATH: " + local_file_path) + print("DIRNAME: " + os.path.dirname(local_file_path)) + + # Ensure the directory exists + if not os.path.exists(os.path.dirname(local_file_path)): + os.makedirs(os.path.dirname(local_file_path), exist_ok=True) + + with requests.get(true_url, stream=True) as r: + r.raise_for_status() + with open(local_file_path, 'wb') as f: + shutil.copyfileobj(r.raw, f) + # If the path starts with 'static', use the true_url - if path.startswith('static') or path.startswith('assets') or path.startswith('api/rails/active_storage'): - response = requests.get(true_url, stream=True) - if response.status_code == 200: - # Create a FileResponse from the content of the downloaded file - file_response = FileResponse(response.content, content_type=response.headers['Content-Type']) - - file_response['Access-Control-Allow-Origin'] = '*' - return file_response - else: - return HttpResponse(f"Error: {response.status_code}. Could not fetch static file from {true_url}", status=response.status_code) - else: - # Send the proxied request to the upstream service - response = requests.request( - method=request.method, - url=proxy_url, - data=request.body, - headers=headers, - files=files, - cookies=request.COOKIES, - allow_redirects=True, - ) + print("PATHPATHPATHPATHPATH: " + path) + # Send the proxied request to the upstream service + response = requests.request( + method=request.method, + url=proxy_url, + data=request.body, + headers=headers, + files=files, + cookies=request.COOKIES, + allow_redirects=True, + ) # Create a Django HttpResponse from the upstream response proxy_response = HttpResponse( content=response.content, status=response.status_code, - #content_type=response.headers['Content-Type'] ) # Add the Access-Control-Allow-Origin header