Files
deerflow-code/offline-backend-20260512/backend/app/gateway/routers/goview_map_tiles.py
T

56 lines
1.7 KiB
Python

"""Controlled XYZ tiles for the offline Leaflet background."""
from __future__ import annotations
import os
import re
from pathlib import Path
from fastapi import APIRouter
from fastapi.responses import FileResponse
from app.gateway.goview_http import fail
from deerflow.config.runtime_paths import runtime_home
router = APIRouter(prefix="/api/goview/map-tiles", tags=["goview-map-tiles"])
_STYLE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$")
_MAX_ZOOM = 22
class TilePathRejected(ValueError):
"""style, zoom, or the resolved path is outside the mounted tile tree."""
def tile_root() -> Path:
override = os.environ.get("DEERFLOW_GOVIEW_TILE_ROOT", "").strip()
if override:
return Path(override).resolve()
return (runtime_home() / "goview-map-tiles").resolve()
def resolve_tile_file(style: str, z: int, x: int, y: int) -> Path:
if not _STYLE_RE.fullmatch(style) or style == "." or ".." in style:
raise TilePathRejected("底图样式无效")
if z < 0 or z > _MAX_ZOOM:
raise TilePathRejected("缩放层级无效")
max_index = (1 << z) - 1
if x < 0 or y < 0 or x > max_index or y > max_index:
raise TilePathRejected("瓦片坐标无效")
root = tile_root()
path = (root / style / str(z) / str(x) / f"{y}.png").resolve()
if not path.is_relative_to(root):
raise TilePathRejected("瓦片路径无效")
return path
@router.get("/{style}/{z}/{x}/{y}.png")
async def read_map_tile(style: str, z: int, x: int, y: int):
try:
path = resolve_tile_file(style, z, x, y)
except TilePathRejected as exc:
return fail(400, str(exc))
if not path.is_file():
return fail(404, "瓦片不存在")
return FileResponse(path, media_type="image/png")