Files
filehost/backend/app/main.py
T
2026-03-08 17:25:31 +05:30

81 lines
2.2 KiB
Python

import mimetypes
import secrets
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from app.config.settings import settings
from app.services.r2 import upload_file
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50 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(
file: UploadFile = File(...),
password: str = Form(...),
):
"""Validate password, enforce size limit, and upload the file to R2."""
if password != settings.UPLOAD_PASSWORD:
raise HTTPException(status_code=401, detail="Invalid password.")
content = await file.read()
if not content:
raise HTTPException(status_code=400, detail="Uploaded file is empty.")
if len(content) > MAX_FILE_SIZE:
mb = len(content) / 1024 / 1024
raise HTTPException(
status_code=413,
detail=f"File is too large ({mb:.1f} MB). Maximum allowed size is 50 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_bytes=content,
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}