coollsd commited on
Commit
5e36128
1 Parent(s): b70a217

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -16
app.py CHANGED
@@ -1,12 +1,17 @@
1
- from fastapi import FastAPI, File, UploadFile, Request
2
  from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
3
  import aiohttp
4
  import asyncio
5
  from typing import Dict
6
  import io
 
7
 
8
  app = FastAPI()
9
 
 
 
 
 
10
  HTML_CONTENT = """
11
  <!DOCTYPE html>
12
  <html lang="en">
@@ -916,24 +921,28 @@ async def index():
916
  @app.post("/upload")
917
  async def handle_upload(file: UploadFile = File(...)):
918
  if not file.filename:
919
- return JSONResponse(content={"error": "No file selected."}, status_code=400)
920
 
921
- cookies = await get_cookies()
922
- if 'csrftoken' not in cookies or 'sessionid' not in cookies:
923
- return JSONResponse(content={"error": "Failed to get cookies"}, status_code=500)
 
924
 
925
- upload_result = await initiate_upload(cookies, file.filename, file.content_type)
926
- if not upload_result or 'upload_url' not in upload_result:
927
- return JSONResponse(content={"error": "Failed to initiate upload"}, status_code=500)
928
 
929
- upload_success = await chunked_upload(upload_result['upload_url'], file, file.content_type)
930
- if not upload_success:
931
- return JSONResponse(content={"error": "Failed to upload file after multiple attempts"}, status_code=500)
932
 
933
- original_url = upload_result['serving_url']
934
- mirrored_url = f"/rbxg/{original_url.split('/pbxt/')[1]}"
935
 
936
- return JSONResponse(content={"url": mirrored_url})
 
 
 
937
 
938
  @app.get("/rbxg/{path:path}")
939
  async def handle_video_stream(path: str, request: Request):
@@ -1019,6 +1028,8 @@ async def initiate_upload(cookies: Dict[str, str], filename: str, content_type:
1019
  }
1020
  async with aiohttp.ClientSession() as session:
1021
  async with session.post(url, cookies=cookies, headers=headers) as response:
 
 
1022
  return await response.json()
1023
 
1024
  async def chunked_upload(upload_url: str, file: UploadFile, content_type: str, chunk_size: int = 1024 * 1024) -> bool:
@@ -1046,7 +1057,7 @@ async def chunked_upload(upload_url: str, file: UploadFile, content_type: str, c
1046
  raise aiohttp.ClientError(f"Unexpected status code: {response.status}")
1047
  except aiohttp.ClientError as e:
1048
  if attempt == 4: # Last attempt
1049
- print(f"Upload failed: {str(e)}")
1050
  return False
1051
  await asyncio.sleep(2 ** attempt) # Exponential backoff
1052
  else:
@@ -1055,7 +1066,7 @@ async def chunked_upload(upload_url: str, file: UploadFile, content_type: str, c
1055
  # Verify the upload
1056
  async with session.put(upload_url, headers={'Content-Range': f'bytes */{file_size}'}) as response:
1057
  if response.status not in [200, 201, 204]:
1058
- print(f"Upload verification failed: {response.status}")
1059
  return False
1060
 
1061
  return True
 
1
+ from fastapi import FastAPI, File, UploadFile, Request, HTTPException
2
  from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
3
  import aiohttp
4
  import asyncio
5
  from typing import Dict
6
  import io
7
+ import logging
8
 
9
  app = FastAPI()
10
 
11
+ # Set up logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
  HTML_CONTENT = """
16
  <!DOCTYPE html>
17
  <html lang="en">
 
921
  @app.post("/upload")
922
  async def handle_upload(file: UploadFile = File(...)):
923
  if not file.filename:
924
+ raise HTTPException(status_code=400, detail="No file selected.")
925
 
926
+ try:
927
+ cookies = await get_cookies()
928
+ if 'csrftoken' not in cookies or 'sessionid' not in cookies:
929
+ raise HTTPException(status_code=500, detail="Failed to get cookies")
930
 
931
+ upload_result = await initiate_upload(cookies, file.filename, file.content_type)
932
+ if not upload_result or 'upload_url' not in upload_result:
933
+ raise HTTPException(status_code=500, detail="Failed to initiate upload")
934
 
935
+ upload_success = await chunked_upload(upload_result['upload_url'], file, file.content_type)
936
+ if not upload_success:
937
+ raise HTTPException(status_code=500, detail="Failed to upload file after multiple attempts")
938
 
939
+ original_url = upload_result['serving_url']
940
+ mirrored_url = f"/rbxg/{original_url.split('/pbxt/')[1]}"
941
 
942
+ return JSONResponse(content={"url": mirrored_url})
943
+ except Exception as e:
944
+ logger.error(f"Upload error: {str(e)}")
945
+ raise HTTPException(status_code=500, detail=str(e))
946
 
947
  @app.get("/rbxg/{path:path}")
948
  async def handle_video_stream(path: str, request: Request):
 
1028
  }
1029
  async with aiohttp.ClientSession() as session:
1030
  async with session.post(url, cookies=cookies, headers=headers) as response:
1031
+ if response.status != 200:
1032
+ raise HTTPException(status_code=response.status, detail=f"Failed to initiate upload: {await response.text()}")
1033
  return await response.json()
1034
 
1035
  async def chunked_upload(upload_url: str, file: UploadFile, content_type: str, chunk_size: int = 1024 * 1024) -> bool:
 
1057
  raise aiohttp.ClientError(f"Unexpected status code: {response.status}")
1058
  except aiohttp.ClientError as e:
1059
  if attempt == 4: # Last attempt
1060
+ logger.error(f"Upload failed: {str(e)}")
1061
  return False
1062
  await asyncio.sleep(2 ** attempt) # Exponential backoff
1063
  else:
 
1066
  # Verify the upload
1067
  async with session.put(upload_url, headers={'Content-Range': f'bytes */{file_size}'}) as response:
1068
  if response.status not in [200, 201, 204]:
1069
+ logger.error(f"Upload verification failed: {response.status}")
1070
  return False
1071
 
1072
  return True