Files
SakuraHub/sakura_cloud/api/v1/endpoints/files.py
T

50 lines
2.0 KiB
Python
Raw Normal View History

2026-11-16 20:45:22 +08:00
from __future__ import annotations
from pathlib import Path
from fastapi import APIRouter, HTTPException, status
from fastapi.responses import FileResponse
from sakura_cloud.api.deps import CurrentUser, DbSession
from sakura_cloud.models.file import FileBlob, UserFile
from sakura_cloud.services.thumbnails import generate_webp_thumbnail
router = APIRouter()
def _owned_user_file(file_id: str, current_user: CurrentUser, db: DbSession) -> tuple[UserFile, FileBlob]:
user_file = db.get(UserFile, file_id)
if user_file is None or user_file.user_id != current_user.id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="File not found")
blob = db.get(FileBlob, user_file.file_sha256)
if blob is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Blob not found")
return user_file, blob
@router.get("/{file_id}/content")
def file_content(file_id: str, current_user: CurrentUser, db: DbSession) -> FileResponse:
user_file, blob = _owned_user_file(file_id, current_user, db)
path = Path(blob.storage_path)
if not path.is_file():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="File missing from storage")
return FileResponse(path, media_type=blob.mime_type, filename=user_file.original_name)
@router.get("/{file_id}/thumbnail")
def file_thumbnail(file_id: str, current_user: CurrentUser, db: DbSession) -> FileResponse:
_, blob = _owned_user_file(file_id, current_user, db)
if not blob.thumbnail_path:
blob.thumbnail_path = generate_webp_thumbnail(blob.storage_path)
db.commit()
db.refresh(blob)
path = Path(blob.thumbnail_path or blob.storage_path)
if not path.is_file():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Thumbnail missing from storage")
media_type = "image/webp" if path.suffix.lower() == ".webp" else blob.mime_type
return FileResponse(
path,
media_type=media_type,
headers={"Cache-Control": "private, max-age=604800"},
)