"""PocketBase `social_trips` — primary SoT when admin credentials work.""" from __future__ import annotations import logging import time from typing import Any import httpx from .config import ( PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD, PB_URL, SOCIAL_GEO_USE_PB, SOCIAL_TRIPS_COLLECTION, ) log = logging.getLogger("social_svc.geo_pb") _token: str | None = None _token_at = 0.0 _ensured = False def pb_enabled() -> bool: return bool( SOCIAL_GEO_USE_PB and PB_URL and PB_ADMIN_EMAIL and PB_ADMIN_PASSWORD ) def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) def _auth_token() -> str | None: global _token, _token_at if not pb_enabled(): return None if _token and (time.time() - _token_at) < 300: return _token base = PB_URL.rstrip("/") try: with httpx.Client(timeout=8.0) as client: # PB 0.22+ superusers; fall back to legacy admins for path in ( "/api/collections/_superusers/auth-with-password", "/api/admins/auth-with-password", ): r = client.post( f"{base}{path}", json={"identity": PB_ADMIN_EMAIL, "password": PB_ADMIN_PASSWORD}, ) if r.status_code < 400: data = r.json() tok = data.get("token") if tok: _token = str(tok) _token_at = time.time() return _token except Exception as exc: # pragma: no cover log.warning("pb auth failed: %s", exc) return None def _headers() -> dict[str, str] | None: tok = _auth_token() if not tok: return None return {"Authorization": tok} def ensure_collection() -> bool: """Best-effort create `social_trips` collection if missing.""" global _ensured if _ensured: return True headers = _headers() if not headers: return False base = PB_URL.rstrip("/") name = SOCIAL_TRIPS_COLLECTION try: with httpx.Client(timeout=12.0) as client: chk = client.get(f"{base}/api/collections/{name}", headers=headers) if chk.status_code == 200: _ensured = True return True body = { "name": name, "type": "base", "listRule": "", "viewRule": "", "createRule": "", "updateRule": "", "deleteRule": "", "fields": [ {"name": "guest_id", "type": "text", "required": True}, {"name": "city_id", "type": "text", "required": False}, {"name": "city", "type": "text", "required": True}, {"name": "country", "type": "text", "required": False}, {"name": "lat", "type": "number", "required": False}, {"name": "lng", "type": "number", "required": False}, {"name": "h3_cell", "type": "text", "required": False}, {"name": "arrival_date", "type": "text", "required": False}, {"name": "departure_date", "type": "text", "required": False}, { "name": "visibility", "type": "select", "required": True, "maxSelect": 1, "values": ["public", "friends", "private"], }, { "name": "status", "type": "select", "required": True, "maxSelect": 1, "values": ["here", "planned", "past"], }, {"name": "updated_at", "type": "text", "required": True}, ], "indexes": [ "CREATE INDEX idx_social_trips_guest ON social_trips (guest_id)", "CREATE INDEX idx_social_trips_city ON social_trips (city_id)", ], } # PocketBase 0.22+ uses `fields`; older used `schema` created = client.post( f"{base}/api/collections", headers=headers, json=body, ) if created.status_code >= 400: body_legacy = { "name": name, "type": "base", "listRule": None, "viewRule": None, "createRule": None, "updateRule": None, "deleteRule": None, "schema": [ {"name": "guest_id", "type": "text", "required": True}, {"name": "city_id", "type": "text", "required": False}, {"name": "city", "type": "text", "required": True}, {"name": "country", "type": "text", "required": False}, {"name": "lat", "type": "number", "required": False}, {"name": "lng", "type": "number", "required": False}, {"name": "h3_cell", "type": "text", "required": False}, {"name": "arrival_date", "type": "text", "required": False}, {"name": "departure_date", "type": "text", "required": False}, { "name": "visibility", "type": "select", "required": True, "options": {"maxSelect": 1, "values": ["public", "friends", "private"]}, }, { "name": "status", "type": "select", "required": True, "options": {"maxSelect": 1, "values": ["here", "planned", "past"]}, }, {"name": "updated_at", "type": "text", "required": True}, ], } created = client.post( f"{base}/api/collections", headers=headers, json=body_legacy, ) if created.status_code < 400: _ensured = True log.info("created PocketBase collection %s", name) return True log.warning("pb create collection failed: %s %s", created.status_code, created.text[:200]) except Exception as exc: # pragma: no cover log.warning("pb ensure_collection: %s", exc) return False def _rec_to_trip(rec: dict[str, Any]) -> dict[str, Any]: return { "id": rec.get("id") or "", "guest_id": rec.get("guest_id") or "", "city_id": rec.get("city_id") or "", "city": rec.get("city") or "", "country": rec.get("country") or "", "lat": rec.get("lat"), "lng": rec.get("lng"), "h3_cell": rec.get("h3_cell") or "", "arrival_date": rec.get("arrival_date") or "", "departure_date": rec.get("departure_date") or "", "visibility": rec.get("visibility") or "public", "status": rec.get("status") or "planned", "updated_at": rec.get("updated_at") or "", } def list_trips( *, guest_id: str | None = None, city_id: str | None = None, visibility: str | None = "public", status: str | None = None, limit: int = 200, ) -> list[dict[str, Any]] | None: """Return trips from PB, or None if PB unavailable (caller falls back to SQLite).""" headers = _headers() if not headers: return None ensure_collection() filters: list[str] = [] if guest_id: filters.append(f'guest_id="{guest_id}"') if city_id: filters.append(f'city_id="{city_id}"') if visibility: filters.append(f'visibility="{visibility}"') if status: filters.append(f'status="{status}"') params: dict[str, Any] = { "page": 1, "perPage": max(1, min(limit, 500)), "sort": "-updated_at", } if filters: params["filter"] = " && ".join(filters) base = PB_URL.rstrip("/") col = SOCIAL_TRIPS_COLLECTION try: with httpx.Client(timeout=10.0) as client: r = client.get( f"{base}/api/collections/{col}/records", headers=headers, params=params, ) if r.status_code >= 400: return None items = r.json().get("items") or [] return [_rec_to_trip(x) for x in items if isinstance(x, dict)] except Exception as exc: # pragma: no cover log.warning("pb list_trips: %s", exc) return None def upsert_trip(trip: dict[str, Any]) -> dict[str, Any] | None: headers = _headers() if not headers: return None ensure_collection() base = PB_URL.rstrip("/") col = SOCIAL_TRIPS_COLLECTION payload = { "guest_id": trip["guest_id"], "city_id": trip.get("city_id") or "", "city": trip["city"], "country": trip.get("country") or "", "lat": trip.get("lat"), "lng": trip.get("lng"), "h3_cell": trip.get("h3_cell") or "", "arrival_date": trip.get("arrival_date") or "", "departure_date": trip.get("departure_date") or "", "visibility": trip.get("visibility") or "public", "status": trip.get("status") or "planned", "updated_at": trip.get("updated_at") or _now(), } tid = trip.get("id") or "" try: with httpx.Client(timeout=10.0) as client: if tid: r = client.patch( f"{base}/api/collections/{col}/records/{tid}", headers=headers, json=payload, ) if r.status_code >= 400: # maybe id is sqlite-local; create new r = client.post( f"{base}/api/collections/{col}/records", headers=headers, json=payload, ) else: r = client.post( f"{base}/api/collections/{col}/records", headers=headers, json=payload, ) if r.status_code >= 400: log.warning("pb upsert_trip failed: %s", r.text[:200]) return None return _rec_to_trip(r.json()) except Exception as exc: # pragma: no cover log.warning("pb upsert_trip: %s", exc) return None def delete_trip(trip_id: str, guest_id: str) -> bool | None: """True deleted, False not found/forbidden, None PB down.""" headers = _headers() if not headers: return None ensure_collection() base = PB_URL.rstrip("/") col = SOCIAL_TRIPS_COLLECTION try: with httpx.Client(timeout=8.0) as client: get = client.get( f"{base}/api/collections/{col}/records/{trip_id}", headers=headers, ) if get.status_code == 404: return False if get.status_code >= 400: return None rec = get.json() if (rec.get("guest_id") or "") != guest_id: return False d = client.delete( f"{base}/api/collections/{col}/records/{trip_id}", headers=headers, ) return d.status_code < 400 except Exception as exc: # pragma: no cover log.warning("pb delete_trip: %s", exc) return None