Initial commit

This commit is contained in:
subodh committed 2026-03-08 17:25:31 +05:30
commit 0e35933ee3
19 files changed
+3217

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+16
View File
@@ -0,0 +1,16 @@
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
R2_ENDPOINT: str
R2_ACCESS_KEY: str
R2_SECRET_KEY: str
R2_BUCKET: str
PUBLIC_URL: str
UPLOAD_PASSWORD: str
class Config:
env_file = ".env"
settings = Settings()
+80
View File
@@ -0,0 +1,80 @@
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}
View File
Whitespace-only changes.
+47
View File
@@ -0,0 +1,47 @@
import asyncio
from functools import lru_cache
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from app.config.settings import settings
@lru_cache(maxsize=1)
def _get_r2_client():
"""Return a module-level singleton boto3 S3 client for R2."""
return boto3.client(
"s3",
endpoint_url=settings.R2_ENDPOINT,
aws_access_key_id=settings.R2_ACCESS_KEY,
aws_secret_access_key=settings.R2_SECRET_KEY,
config=Config(signature_version="s3v4"),
region_name="auto",
)
def _put_object(object_name: str, file_bytes: bytes, content_type: str) -> str:
"""Blocking S3 put"""
key = f"files/{object_name}"
_get_r2_client().put_object(
Bucket=settings.R2_BUCKET,
Key=key,
Body=file_bytes,
ContentType=content_type,
)
return f"{settings.PUBLIC_URL}/files/{object_name}"
async def upload_file(file_bytes: bytes, object_name: str, content_type: str) -> str:
"""Upload a file to R2 storage"""
try:
url = await asyncio.to_thread(
_put_object, object_name, file_bytes, content_type
)
except (BotoCoreError, ClientError) as exc:
raise RuntimeError(f"R2 upload failed: {exc}") from exc
return url