96 lines
3.1 KiB
Python
96 lines
3.1 KiB
Python
"""Station config router: read/update the singleton station branding config."""
|
|
|
|
import os
|
|
import uuid
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile, status
|
|
|
|
from app.auth import get_current_admin_user
|
|
from app.database import get_session
|
|
from app.models import StationConfig
|
|
from app.schemas import StationConfigResponse, StationConfigUpdate
|
|
from app.user_models import User
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
router = APIRouter()
|
|
|
|
UPLOAD_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "uploads")
|
|
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5 MB
|
|
|
|
|
|
@router.get("", response_model=StationConfigResponse)
|
|
async def get_station_config(session: AsyncSession = Depends(get_session)):
|
|
"""Return the singleton station config. Public endpoint."""
|
|
result = await session.execute(
|
|
select(StationConfig).where(StationConfig.key == "default")
|
|
)
|
|
config = result.scalar_one_or_none()
|
|
if config is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Station config not found. Run seed to initialize.",
|
|
)
|
|
return config
|
|
|
|
|
|
@router.put("", response_model=StationConfigResponse)
|
|
async def update_station_config(
|
|
payload: StationConfigUpdate,
|
|
session: AsyncSession = Depends(get_session),
|
|
current_user: User = Depends(get_current_admin_user),
|
|
):
|
|
"""Partial update of station config. Admin only."""
|
|
result = await session.execute(
|
|
select(StationConfig).where(StationConfig.key == "default")
|
|
)
|
|
config = result.scalar_one_or_none()
|
|
if config is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Station config not found")
|
|
|
|
for key, value in payload.model_dump(exclude_unset=True).items():
|
|
setattr(config, key, value)
|
|
|
|
await session.commit()
|
|
await session.refresh(config)
|
|
return config
|
|
|
|
|
|
@router.post("/upload")
|
|
async def upload_image(
|
|
file: UploadFile,
|
|
current_user: User = Depends(get_current_admin_user),
|
|
):
|
|
"""Upload an image file for station branding. Admin only.
|
|
|
|
Saves the file to the uploads/ directory with a UUID filename.
|
|
Returns the relative URL path.
|
|
"""
|
|
# Validate MIME type
|
|
if not file.content_type or not file.content_type.startswith("image/"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Only image files are allowed",
|
|
)
|
|
|
|
# Read and validate size
|
|
content = await file.read()
|
|
if len(content) > MAX_FILE_SIZE:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="File size exceeds 5 MB limit",
|
|
)
|
|
|
|
# Ensure upload directory exists
|
|
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
|
|
|
# Generate unique filename preserving extension
|
|
ext = os.path.splitext(file.filename or "upload")[1] if file.filename else ".bin"
|
|
filename = f"{uuid.uuid4().hex}{ext}"
|
|
filepath = os.path.join(UPLOAD_DIR, filename)
|
|
|
|
with open(filepath, "wb") as f:
|
|
f.write(content)
|
|
|
|
return {"url": f"uploads/{filename}"}
|