72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
"""Offline map pack API: estimate, create, list, status, delete, tile serving."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from fastapi.responses import FileResponse
|
|
from pydantic import BaseModel, Field
|
|
|
|
from app.deps import get_offline_maps, get_store
|
|
from app.services.offline_maps import estimate_tile_count
|
|
|
|
router = APIRouter(prefix="/api/offline-maps", tags=["offline-maps"])
|
|
|
|
AVG_TILE_BYTES = 25_000 # rough raster tile size for the pre-download estimate
|
|
|
|
|
|
class PackBody(BaseModel):
|
|
name: str = "Offline area"
|
|
bbox: list[float] = Field(min_length=4, max_length=4) # [min_lon, min_lat, max_lon, max_lat]
|
|
min_zoom: int = Field(8, ge=0, le=16)
|
|
max_zoom: int = Field(14, ge=0, le=16)
|
|
layers: list[str] = Field(default_factory=lambda: ["base", "terrain"])
|
|
|
|
|
|
@router.post("/estimate")
|
|
def estimate(body: PackBody):
|
|
if body.max_zoom < body.min_zoom:
|
|
raise HTTPException(400, "max_zoom must be >= min_zoom")
|
|
count = estimate_tile_count(body.bbox, body.min_zoom, body.max_zoom) * len(body.layers)
|
|
return {"tile_count": count, "estimated_bytes": count * AVG_TILE_BYTES}
|
|
|
|
|
|
@router.post("")
|
|
def create_pack(body: PackBody):
|
|
if body.max_zoom < body.min_zoom:
|
|
raise HTTPException(400, "max_zoom must be >= min_zoom")
|
|
try:
|
|
return get_offline_maps().create_pack(
|
|
body.name, body.bbox, body.min_zoom, body.max_zoom, body.layers
|
|
)
|
|
except ValueError as e:
|
|
raise HTTPException(400, str(e))
|
|
|
|
|
|
@router.get("")
|
|
def list_packs():
|
|
return get_store().list_map_packs()
|
|
|
|
|
|
@router.get("/{pack_id}")
|
|
def get_pack(pack_id: str):
|
|
pack = get_store().get_map_pack(pack_id)
|
|
if pack is None:
|
|
raise HTTPException(404, "map pack not found")
|
|
return pack
|
|
|
|
|
|
@router.delete("/{pack_id}")
|
|
def delete_pack(pack_id: str):
|
|
if not get_offline_maps().delete_pack(pack_id):
|
|
raise HTTPException(404, "map pack not found")
|
|
return {"deleted": pack_id}
|
|
|
|
|
|
@router.get("/tiles/{layer}/{z}/{x}/{y}.png")
|
|
def serve_tile(layer: str, z: int, x: int, y: int):
|
|
"""Serve a tile from any ready pack (the UI's offline tile source)."""
|
|
path = get_offline_maps().find_tile(layer, z, x, y)
|
|
if path is None:
|
|
raise HTTPException(404, "tile not in any offline pack")
|
|
return FileResponse(path, media_type="image/png")
|