79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
import mimetypes
|
|
import secrets
|
|
|
|
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from app.config.settings import settings
|
|
from app.services.r2 import upload_file
|
|
|
|
MAX_FILE_SIZE = 250 * 1024 * 1024 # 250 MB
|
|
|
|
app = FastAPI(title="File Host API")
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["https://filehost.subodh.xyz"],
|
|
allow_methods=["POST"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
def _resolve_object_name(filename: str, content_type: str) -> str:
|
|
file_id = secrets.token_urlsafe(16)
|
|
|
|
ext = ""
|
|
if filename and "." in filename:
|
|
ext = filename.rsplit(".", 1)[-1].strip().lower()
|
|
|
|
if not ext and content_type:
|
|
guessed = mimetypes.guess_extension(content_type.split(";")[0].strip())
|
|
if guessed:
|
|
ext = guessed.lstrip(".")
|
|
|
|
return f"{file_id}.{ext}" if ext else file_id
|
|
|
|
|
|
@app.post("/auth")
|
|
async def auth(password: str = Form(...)):
|
|
"""Validate the upload password."""
|
|
if password != settings.UPLOAD_PASSWORD:
|
|
raise HTTPException(status_code=401, detail="Invalid password.")
|
|
return {"valid": True}
|
|
|
|
|
|
@app.post("/upload")
|
|
async def upload(
|
|
request: Request,
|
|
file: UploadFile = File(...),
|
|
password: str = Form(...),
|
|
):
|
|
"""Validate password, enforce size limit, and stream the file to R2."""
|
|
if password != settings.UPLOAD_PASSWORD:
|
|
raise HTTPException(status_code=401, detail="Invalid password.")
|
|
|
|
# Reject oversized requests early, before reading the body.
|
|
# Content-Length covers the whole multipart body; form overhead is negligible.
|
|
content_length = request.headers.get("content-length")
|
|
if content_length and int(content_length) > MAX_FILE_SIZE:
|
|
raise HTTPException(
|
|
status_code=413,
|
|
detail="File too large. Maximum allowed size is 250 MB.",
|
|
)
|
|
|
|
content_type = (
|
|
(file.content_type or "application/octet-stream").split(";")[0].strip()
|
|
)
|
|
object_name = _resolve_object_name(file.filename or "", content_type)
|
|
|
|
try:
|
|
url = await upload_file(
|
|
file_obj=file.file,
|
|
object_name=object_name,
|
|
content_type=content_type,
|
|
)
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
|
|
|
return {"url": url}
|