Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README. Co-authored-by: Cursor <cursoragent@cursor.com>
231 lines
7.5 KiB
Python
231 lines
7.5 KiB
Python
"""Geo discovery API — map cities, Photon search, trips, overlaps."""
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Header, HTTPException, Query
|
|
from pydantic import BaseModel, Field
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from social_svc import geo_store, photon
|
|
from social_svc.config import SOCIAL_ENABLED
|
|
from social_svc.geo_cities import list_seed_cities, city_public
|
|
|
|
router = APIRouter(tags=["social-geo"])
|
|
|
|
|
|
def _guest(
|
|
x_social_guest_id: str | None,
|
|
guest_q: str | None = None,
|
|
) -> str:
|
|
gid = (x_social_guest_id or guest_q or "").strip()
|
|
if not gid or len(gid) > 80:
|
|
raise HTTPException(status_code=400, detail="missing X-Social-Guest-Id")
|
|
return gid
|
|
|
|
|
|
class TripIn(BaseModel):
|
|
city: str = Field(min_length=1, max_length=80)
|
|
city_id: str = Field(default="", max_length=64)
|
|
country: str = Field(default="", max_length=64)
|
|
lat: float | None = None
|
|
lng: float | None = None
|
|
arrival_date: str = Field(default="", max_length=10)
|
|
departure_date: str = Field(default="", max_length=10)
|
|
visibility: str = Field(default="public", max_length=16)
|
|
status: str = Field(default="planned", max_length=16)
|
|
|
|
|
|
class TripPatch(BaseModel):
|
|
city: str | None = Field(default=None, max_length=80)
|
|
city_id: str | None = Field(default=None, max_length=64)
|
|
country: str | None = Field(default=None, max_length=64)
|
|
lat: float | None = None
|
|
lng: float | None = None
|
|
arrival_date: str | None = Field(default=None, max_length=10)
|
|
departure_date: str | None = Field(default=None, max_length=10)
|
|
visibility: str | None = Field(default=None, max_length=16)
|
|
status: str | None = Field(default=None, max_length=16)
|
|
|
|
|
|
@router.get("/map/cities")
|
|
async def map_cities(
|
|
west: float | None = None,
|
|
south: float | None = None,
|
|
east: float | None = None,
|
|
north: float | None = None,
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
items = await run_in_threadpool(geo_store.map_cities)
|
|
if None not in (west, south, east, north):
|
|
items = [
|
|
c
|
|
for c in items
|
|
if west <= float(c["lng"]) <= east and south <= float(c["lat"]) <= north # type: ignore[operator]
|
|
]
|
|
return {"items": items, "source": "seed+trips"}
|
|
|
|
|
|
@router.get("/cities/search")
|
|
async def cities_search(
|
|
q: str = Query(default="", max_length=80),
|
|
limit: int = Query(default=8, ge=1, le=20),
|
|
lang: str = Query(default="zh", max_length=8),
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
query = (q or "").strip().lower()
|
|
seed_hits = []
|
|
if query:
|
|
for c in list_seed_cities():
|
|
hay = f"{c['name']} {c['country']} {' '.join(c.get('tags') or [])}".lower()
|
|
if query in hay:
|
|
seed_hits.append(city_public(c, extras={"source": "seed"}))
|
|
photon_hits = await photon.search_cities(q, limit=limit, lang=lang)
|
|
# Prefer seed ids when names collide
|
|
seed_names = {c["name"] for c in seed_hits}
|
|
merged = list(seed_hits)
|
|
for p in photon_hits:
|
|
if p["name"] in seed_names:
|
|
continue
|
|
merged.append(p)
|
|
return {"items": merged[:limit], "q": q}
|
|
|
|
|
|
@router.get("/cities/{city_id}")
|
|
async def city_detail(city_id: str):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
item = await run_in_threadpool(geo_store.city_detail, city_id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="city not found")
|
|
return {"item": item}
|
|
|
|
|
|
@router.get("/people")
|
|
async def people_geo(
|
|
city: str = Query(default="", max_length=80),
|
|
cityId: str = Query(default="", max_length=64),
|
|
status: str = Query(default="", max_length=16),
|
|
profession: str = Query(default="", max_length=80),
|
|
interest: str = Query(default="", max_length=80),
|
|
language: str = Query(default="", max_length=40),
|
|
currentlyHere: bool = Query(default=False),
|
|
arrivingSoon: bool = Query(default=False),
|
|
limit: int = Query(default=40, ge=1, le=100),
|
|
):
|
|
"""Public trip-backed presence filter (no lat/lng). Seed roster still lives client-side."""
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
|
|
def _run() -> list[dict[str, Any]]:
|
|
vis = "public"
|
|
st = None
|
|
if currentlyHere:
|
|
st = "here"
|
|
elif arrivingSoon:
|
|
st = "planned"
|
|
elif status in {"here", "planned", "past"}:
|
|
st = status
|
|
trips = geo_store.list_trips(
|
|
city_id=cityId or None,
|
|
visibility=vis,
|
|
status=st,
|
|
limit=limit * 3,
|
|
)
|
|
out: list[dict[str, Any]] = []
|
|
for t in trips:
|
|
if city and city.lower() not in (t.get("city") or "").lower():
|
|
continue
|
|
# profession/interest/language reserved for roster join later
|
|
_ = (profession, interest, language)
|
|
out.append(
|
|
{
|
|
"guestId": (t.get("guest_id") or "")[:10],
|
|
"city": t.get("city"),
|
|
"cityId": t.get("city_id") or "",
|
|
"status": t.get("status"),
|
|
"arrival_date": t.get("arrival_date") or "",
|
|
"departure_date": t.get("departure_date") or "",
|
|
"h3Res": t.get("h3_cell") or "",
|
|
}
|
|
)
|
|
if len(out) >= limit:
|
|
break
|
|
return out
|
|
|
|
items = await run_in_threadpool(_run)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/travel-overlaps")
|
|
async def travel_overlaps(
|
|
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
|
guest_id: str | None = Query(default=None),
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
gid = _guest(x_social_guest_id, guest_id)
|
|
items = await run_in_threadpool(geo_store.travel_overlaps, gid)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/trips")
|
|
async def list_my_trips(
|
|
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
|
guest_id: str | None = Query(default=None),
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
gid = _guest(x_social_guest_id, guest_id)
|
|
items = await run_in_threadpool(
|
|
lambda: geo_store.list_trips(guest_id=gid, visibility=None, limit=100)
|
|
)
|
|
return {"items": items}
|
|
|
|
|
|
@router.post("/trips")
|
|
async def create_trip(
|
|
body: TripIn,
|
|
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
gid = _guest(x_social_guest_id)
|
|
try:
|
|
item = await run_in_threadpool(geo_store.create_trip, gid, body.model_dump())
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
return {"item": item}
|
|
|
|
|
|
@router.patch("/trips/{trip_id}")
|
|
async def patch_trip(
|
|
trip_id: str,
|
|
body: TripPatch,
|
|
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
gid = _guest(x_social_guest_id)
|
|
payload = {k: v for k, v in body.model_dump().items() if v is not None}
|
|
item = await run_in_threadpool(geo_store.update_trip, gid, trip_id, payload)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="trip not found")
|
|
return {"item": item}
|
|
|
|
|
|
@router.delete("/trips/{trip_id}")
|
|
async def remove_trip(
|
|
trip_id: str,
|
|
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
|
):
|
|
if not SOCIAL_ENABLED:
|
|
raise HTTPException(status_code=503, detail="social disabled")
|
|
gid = _guest(x_social_guest_id)
|
|
ok = await run_in_threadpool(geo_store.delete_trip, gid, trip_id)
|
|
if not ok:
|
|
raise HTTPException(status_code=404, detail="trip not found")
|
|
return {"ok": True}
|