-
This commit is contained in:
@@ -0,0 +1,297 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, File, HTTPException, Query, UploadFile, status
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import func, or_, select, update
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.deps import AnyAdmin, DbSession
|
||||
from app.models import Project, ProjectCategory, ProjectImage, ProjectStatus
|
||||
from app.schemas.common import Page
|
||||
from app.schemas.project import (
|
||||
ProjectAdmin,
|
||||
ProjectCreate,
|
||||
ProjectImageAdmin,
|
||||
ProjectImageUpdate,
|
||||
ProjectPublicDetail,
|
||||
ProjectPublicSummary,
|
||||
ProjectUpdate,
|
||||
UploadResult,
|
||||
)
|
||||
from app.services.image_processing import (
|
||||
ImageValidationError,
|
||||
StoredImage,
|
||||
WatermarkUnavailableError,
|
||||
delete_media_files,
|
||||
load_logo,
|
||||
process_image,
|
||||
read_upload,
|
||||
resolve_media_path,
|
||||
)
|
||||
from app.utils.helpers import escape_like, paginate, unique_slug
|
||||
|
||||
public_router = APIRouter(prefix="/projects", tags=["Projects"])
|
||||
admin_router = APIRouter(prefix="/admin/projects", tags=["Admin: projects"])
|
||||
images_router = APIRouter(prefix="/admin/project-images", tags=["Admin: project images"])
|
||||
|
||||
|
||||
async def _load_project(db, project_id: int) -> Project:
|
||||
project = await db.scalar(
|
||||
select(Project).where(Project.id == project_id).execution_options(populate_existing=True)
|
||||
)
|
||||
if not project:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Project not found")
|
||||
return project
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ public
|
||||
|
||||
|
||||
@public_router.get("", response_model=Page[ProjectPublicSummary], summary="Published projects")
|
||||
async def list_published_projects(
|
||||
db: DbSession,
|
||||
category: ProjectCategory | None = None,
|
||||
project_status: Annotated[ProjectStatus | None, Query(alias="status")] = None,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 12,
|
||||
):
|
||||
stmt = (
|
||||
select(Project)
|
||||
.where(Project.is_published.is_(True))
|
||||
.order_by(Project.installation_date.desc().nulls_last(), Project.id.desc())
|
||||
)
|
||||
if category:
|
||||
stmt = stmt.where(Project.category == category)
|
||||
if project_status:
|
||||
stmt = stmt.where(Project.status == project_status)
|
||||
rows, total = await paginate(db, stmt, page, page_size)
|
||||
return Page(items=[ProjectPublicSummary.build(p) for p in rows], total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@public_router.get("/{id_or_slug}", response_model=ProjectPublicDetail, summary="Project by id or slug")
|
||||
async def get_published_project(id_or_slug: str, db: DbSession):
|
||||
cond = Project.id == int(id_or_slug) if id_or_slug.isdigit() else Project.slug == id_or_slug
|
||||
project = await db.scalar(select(Project).where(cond, Project.is_published.is_(True)))
|
||||
if not project:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Project not found")
|
||||
return ProjectPublicDetail.build(project)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ admin CRUD
|
||||
|
||||
|
||||
@admin_router.get("", response_model=Page[ProjectAdmin])
|
||||
async def admin_list_projects(
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
search: Annotated[str | None, Query(max_length=100)] = None,
|
||||
category: ProjectCategory | None = None,
|
||||
project_status: Annotated[ProjectStatus | None, Query(alias="status")] = None,
|
||||
is_published: bool | None = None,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 20,
|
||||
):
|
||||
stmt = select(Project).order_by(Project.created_at.desc(), Project.id.desc())
|
||||
if search and (term := search.strip()):
|
||||
like = f"%{escape_like(term)}%"
|
||||
stmt = stmt.where(or_(Project.title.ilike(like), Project.location.ilike(like)))
|
||||
if category:
|
||||
stmt = stmt.where(Project.category == category)
|
||||
if project_status:
|
||||
stmt = stmt.where(Project.status == project_status)
|
||||
if is_published is not None:
|
||||
stmt = stmt.where(Project.is_published.is_(is_published))
|
||||
rows, total = await paginate(db, stmt, page, page_size)
|
||||
return Page(items=[ProjectAdmin.build(p) for p in rows], total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@admin_router.get("/{project_id}", response_model=ProjectAdmin)
|
||||
async def admin_get_project(project_id: int, _: AnyAdmin, db: DbSession):
|
||||
return ProjectAdmin.build(await _load_project(db, project_id))
|
||||
|
||||
|
||||
@admin_router.post("", response_model=ProjectAdmin, status_code=status.HTTP_201_CREATED)
|
||||
async def create_project(body: ProjectCreate, _: AnyAdmin, db: DbSession):
|
||||
data = body.model_dump()
|
||||
data["slug"] = await unique_slug(db, Project, data["slug"] or data["title"])
|
||||
project = Project(**data)
|
||||
db.add(project)
|
||||
await db.commit()
|
||||
return ProjectAdmin.build(await _load_project(db, project.id))
|
||||
|
||||
|
||||
@admin_router.put("/{project_id}", response_model=ProjectAdmin)
|
||||
async def update_project(project_id: int, body: ProjectUpdate, _: AnyAdmin, db: DbSession):
|
||||
project = await _load_project(db, project_id)
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
for required in ("title", "category", "status", "is_published"):
|
||||
if required in data and data[required] is None:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, f"'{required}' cannot be null")
|
||||
if data.get("slug"):
|
||||
data["slug"] = await unique_slug(db, Project, data["slug"], exclude_id=project.id)
|
||||
else:
|
||||
data.pop("slug", None)
|
||||
for key, value in data.items():
|
||||
setattr(project, key, value)
|
||||
await db.commit()
|
||||
return ProjectAdmin.build(await _load_project(db, project_id))
|
||||
|
||||
|
||||
@admin_router.delete("/{project_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_project(project_id: int, _: AnyAdmin, db: DbSession):
|
||||
project = await _load_project(db, project_id)
|
||||
files = [p for img in project.images for p in (img.original_path, img.watermarked_path, img.thumbnail_path)]
|
||||
await db.delete(project)
|
||||
await db.commit()
|
||||
delete_media_files(*files) # only after the DB change succeeded
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ images
|
||||
|
||||
|
||||
@admin_router.post(
|
||||
"/{project_id}/images",
|
||||
response_model=UploadResult,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Upload one or more photos (auto-watermarked)",
|
||||
description=(
|
||||
"Accepts JPG/JPEG/PNG/WEBP. Each file is validated, the original is stored privately, "
|
||||
"a copy with the Saura Shakti logo watermark (bottom-right) is generated, plus a WEBP thumbnail. "
|
||||
"If any file is invalid the whole batch is rejected and nothing is saved."
|
||||
),
|
||||
)
|
||||
async def upload_project_images(
|
||||
project_id: int,
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
files: Annotated[list[UploadFile], File(description="Image files (field name: files)")],
|
||||
):
|
||||
project = await _load_project(db, project_id)
|
||||
if not files:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "No files uploaded")
|
||||
if len(files) > settings.MAX_FILES_PER_UPLOAD:
|
||||
raise HTTPException(
|
||||
status.HTTP_400_BAD_REQUEST, f"Upload at most {settings.MAX_FILES_PER_UPLOAD} files at a time"
|
||||
)
|
||||
try:
|
||||
load_logo()
|
||||
except WatermarkUnavailableError as exc:
|
||||
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from None
|
||||
|
||||
# 1. validate every file before touching disk
|
||||
validated, errors, worst = [], [], status.HTTP_400_BAD_REQUEST
|
||||
for f in files:
|
||||
try:
|
||||
validated.append(await read_upload(f))
|
||||
except ImageValidationError as exc:
|
||||
errors.append(exc.message)
|
||||
worst = exc.status_code
|
||||
if errors:
|
||||
raise HTTPException(worst if len(errors) == 1 else status.HTTP_400_BAD_REQUEST, {"errors": errors})
|
||||
|
||||
# 2. process (watermark + thumbnail) off the event loop
|
||||
stored: list[StoredImage] = []
|
||||
try:
|
||||
for v in validated:
|
||||
stored.append(await run_in_threadpool(process_image, v))
|
||||
|
||||
next_order = (
|
||||
await db.scalar(
|
||||
select(func.coalesce(func.max(ProjectImage.sort_order), -1)).where(
|
||||
ProjectImage.project_id == project.id
|
||||
)
|
||||
)
|
||||
) + 1
|
||||
has_featured = any(img.is_featured for img in project.images)
|
||||
new_rows = []
|
||||
for i, (v, s) in enumerate(zip(validated, stored, strict=True)):
|
||||
row = ProjectImage(
|
||||
project_id=project.id,
|
||||
original_filename=v.original_filename,
|
||||
original_path=s.original_path,
|
||||
watermarked_path=s.watermarked_path,
|
||||
thumbnail_path=s.thumbnail_path,
|
||||
mime_type=s.mime_type,
|
||||
file_size=s.file_size,
|
||||
width=s.width,
|
||||
height=s.height,
|
||||
sort_order=next_order + i,
|
||||
is_featured=not has_featured and i == 0,
|
||||
)
|
||||
db.add(row)
|
||||
new_rows.append(row)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
delete_media_files(*[p for s in stored for p in (s.original_path, s.watermarked_path, s.thumbnail_path)])
|
||||
raise
|
||||
|
||||
project = await _load_project(db, project_id)
|
||||
ids = {r.id for r in new_rows}
|
||||
return UploadResult(
|
||||
uploaded=[ProjectImageAdmin.build(img) for img in project.images if img.id in ids],
|
||||
project=ProjectAdmin.build(project),
|
||||
)
|
||||
|
||||
|
||||
async def _get_image(db, image_id: int) -> ProjectImage:
|
||||
image = await db.get(ProjectImage, image_id)
|
||||
if not image:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Image not found")
|
||||
return image
|
||||
|
||||
|
||||
@images_router.patch("/{image_id}", response_model=ProjectAdmin, summary="Edit caption/order or set as featured")
|
||||
async def update_project_image(image_id: int, body: ProjectImageUpdate, _: AnyAdmin, db: DbSession):
|
||||
image = await _get_image(db, image_id)
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("is_featured") is True:
|
||||
await db.execute(
|
||||
update(ProjectImage)
|
||||
.where(ProjectImage.project_id == image.project_id, ProjectImage.id != image.id)
|
||||
.values(is_featured=False)
|
||||
)
|
||||
await db.flush()
|
||||
for key, value in data.items():
|
||||
if value is None and key in ("sort_order", "is_featured"):
|
||||
continue
|
||||
setattr(image, key, value)
|
||||
await db.commit()
|
||||
return ProjectAdmin.build(await _load_project(db, image.project_id))
|
||||
|
||||
|
||||
@images_router.delete("/{image_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_project_image(image_id: int, _: AnyAdmin, db: DbSession):
|
||||
image = await _get_image(db, image_id)
|
||||
project_id, was_featured = image.project_id, image.is_featured
|
||||
files = (image.original_path, image.watermarked_path, image.thumbnail_path)
|
||||
await db.delete(image)
|
||||
await db.flush()
|
||||
if was_featured: # promote the next image so the project keeps a cover photo
|
||||
next_img = await db.scalar(
|
||||
select(ProjectImage)
|
||||
.where(ProjectImage.project_id == project_id)
|
||||
.order_by(ProjectImage.sort_order, ProjectImage.id)
|
||||
.limit(1)
|
||||
)
|
||||
if next_img:
|
||||
next_img.is_featured = True
|
||||
await db.commit()
|
||||
delete_media_files(*files)
|
||||
|
||||
|
||||
@images_router.get(
|
||||
"/{image_id}/original",
|
||||
response_class=FileResponse,
|
||||
summary="Download the un-watermarked original (admin only)",
|
||||
)
|
||||
async def download_original(image_id: int, _: AnyAdmin, db: DbSession):
|
||||
image = await _get_image(db, image_id)
|
||||
try:
|
||||
path = resolve_media_path(image.original_path)
|
||||
except ValueError:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "File not found") from None
|
||||
if not path.is_file():
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "File not found")
|
||||
return FileResponse(path, media_type=image.mime_type, filename=image.original_filename)
|
||||
Reference in New Issue
Block a user