"""Application chrome name and logo. Stored separately from ``generated_page_branding`` and the ``generated-page-branding/`` directory. An empty name or a missing logo leaves the built-in title and static theme logos in place. """ from __future__ import annotations import asyncio from uuid import uuid4 from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile from fastapi.responses import FileResponse from pydantic import BaseModel from app.gateway.routers.system_settings import _require_admin from deerflow.config.runtime_paths import runtime_home from deerflow.config.system_settings import ( AppIdentitySettings, app_identity_logo_path, load_system_settings, save_system_settings, ) router = APIRouter(prefix="/api/system-settings", tags=["system-settings"]) public_router = APIRouter(prefix="/api/public/app-identity", tags=["app-identity"]) _MAX_LOGO_BYTES = 10 * 1024 * 1024 _PUBLIC_LOGO_PATH = "/api/public/app-identity/logo" class AppIdentityResponse(BaseModel): system_name: str = "" logo_url: str | None = None logo_version: str | None = None has_logo: bool = False def _detect_logo(data: bytes) -> tuple[str, str]: if data.startswith(b"\x89PNG\r\n\x1a\n"): return ".png", "image/png" if data.startswith(b"\xff\xd8\xff"): return ".jpg", "image/jpeg" if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": return ".webp", "image/webp" raise HTTPException(status_code=422, detail="Logo 仅支持 PNG、JPG 或 WebP 图片") def _normalize_system_name(value: str | None) -> str: normalized = " ".join(str(value or "").split()) if len(normalized) > 80: raise HTTPException(status_code=422, detail="系统名称不能超过 80 个字符") return normalized def _response(settings: AppIdentitySettings) -> AppIdentityResponse: path = app_identity_logo_path(settings) version = settings.logo_version if path is not None else None return AppIdentityResponse( system_name=settings.system_name, logo_url=f"{_PUBLIC_LOGO_PATH}?v={version}" if version else None, logo_version=version, has_logo=path is not None, ) def _write_logo(data: bytes, suffix: str) -> str: directory = runtime_home() / "app-identity" directory.mkdir(parents=True, exist_ok=True) filename = f"logo-{uuid4().hex}{suffix}" destination = directory / filename temporary = directory / f".{filename}.tmp" try: temporary.write_bytes(data) temporary.replace(destination) finally: temporary.unlink(missing_ok=True) return filename @router.get("/app-identity", response_model=AppIdentityResponse) async def get_app_identity_settings() -> AppIdentityResponse: """Return the application name and uploaded logo. Any logged-in user may read it.""" return _response(load_system_settings().app_identity) @router.put("/app-identity", response_model=AppIdentityResponse) async def update_app_identity_settings( request: Request, system_name: str = Form(default=""), remove_logo: bool = Form(default=False), logo: UploadFile | None = File(default=None), ) -> AppIdentityResponse: """Save the application chrome name and optional logo. Admin only.""" await _require_admin(request) if logo is not None and remove_logo: raise HTTPException(status_code=422, detail="上传 Logo 时不能同时恢复静态 Logo") current = load_system_settings() previous_logo = app_identity_logo_path(current.app_identity) update: dict[str, object] = {"system_name": _normalize_system_name(system_name)} new_logo_path = None if logo is not None: data = await logo.read(_MAX_LOGO_BYTES + 1) await logo.close() if not data: raise HTTPException(status_code=422, detail="Logo 文件不能为空") if len(data) > _MAX_LOGO_BYTES: raise HTTPException(status_code=413, detail="Logo 文件不能超过 10MB") suffix, media_type = _detect_logo(data) filename = await asyncio.to_thread(_write_logo, data, suffix) new_logo_path = runtime_home() / "app-identity" / filename update.update( { "logo_filename": filename, "logo_media_type": media_type, "logo_version": uuid4().hex, } ) elif remove_logo: update.update( { "logo_filename": None, "logo_media_type": None, "logo_version": None, } ) updated = current.app_identity.model_copy(update=update) try: saved = save_system_settings(current.model_copy(update={"app_identity": updated})) except Exception: if new_logo_path is not None: await asyncio.to_thread(new_logo_path.unlink, missing_ok=True) raise if previous_logo is not None and previous_logo != app_identity_logo_path(saved.app_identity): await asyncio.to_thread(previous_logo.unlink, missing_ok=True) return _response(saved.app_identity) @router.delete("/app-identity", response_model=AppIdentityResponse) async def delete_app_identity_settings(request: Request) -> AppIdentityResponse: """Clear the application name and uploaded logo. Admin only.""" await _require_admin(request) current = load_system_settings() previous_logo = app_identity_logo_path(current.app_identity) saved = save_system_settings(current.model_copy(update={"app_identity": AppIdentitySettings()})) if previous_logo is not None: await asyncio.to_thread(previous_logo.unlink, missing_ok=True) return _response(saved.app_identity) @public_router.get("/logo") async def get_app_identity_logo() -> FileResponse: """Serve the uploaded application logo. Missing logos stay on the static assets.""" settings = load_system_settings().app_identity path = app_identity_logo_path(settings) if path is None: raise HTTPException(status_code=404, detail="未上传系统 Logo") return FileResponse( path, media_type=settings.logo_media_type or "image/png", content_disposition_type="inline", headers={"Cache-Control": "public, max-age=31536000, immutable"}, )