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 UNAUTH_LIMIT = 50 * 1024 * 1024 # 50 MB — unauthenticated AUTH_LIMIT = 250 * 1024 * 1024 # 250 MB — authenticated 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(default=""), ): """ Upload a file to R2. - No password: allowed up to 50 MB. - Correct password: allowed up to 250 MB. - Wrong password (non-empty): rejected with 401. """ if password and password != settings.UPLOAD_PASSWORD: raise HTTPException(status_code=401, detail="Invalid password.") is_authenticated = password == settings.UPLOAD_PASSWORD max_size = AUTH_LIMIT if is_authenticated else UNAUTH_LIMIT limit_str = "250 MB" if is_authenticated else "50 MB" content_length = request.headers.get("content-length") if content_length and int(content_length) > max_size: raise HTTPException( status_code=413, detail=f"File too large. Maximum allowed size is {limit_str}.", ) 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}